svk
svk

Reputation: 4553

Enable and disable the click event for image using Jquery?

I am having the image.When Image is clicked I show the data with some animation.So what I want to do is disable the image upto data shown in browser.Then once data is loaded I need to enable the image.

for example

$("#imageid").click(function(e){
//disable the click
$("idforanim").animate({left : "-=50 "px"},500,function(){callfunction1();})
 })

callfunction1(){
//show the data
//enable the click
}

How can I achieve this?

Upvotes: 2

Views: 9534

Answers (3)

Cymen
Cymen

Reputation: 14419

You can do this by taking advantage of the fact that animate takes a function to call upon completion of the animation. For example:

http://jsbin.com/adokiz/2

What we do is this:

$(document).ready(function() {
    var running = false;
    $('img').on('click', function(event) {
      if (running) return;

      running = true;
      console.log(this);
      $(this).animate({top: '400px'}, function() {
        $(this).css({top: 0});
        running = false;
      });
    });
});

With the global variable named running you can prevent multiple clicks from being recognized at the same time. This isn't exactly the same as your code but you can easily adapt it.

Another way to do this which should be even more resistant to being executed twice is using the jQuery one to bind it like so:

$(document).ready(function() {  
  var animation;

  var binding = function() {
    $('img').one('click', animation);
  };

  animation = function(event) {
    $(event.target).animate({top: '400px'}, function() {
      $(event.target).css({top: 0});
      binding();
    });
  };

  binding();
});

Demo: http://jsbin.com/adokiz/3

Upvotes: 1

Shimon Rachlenko
Shimon Rachlenko

Reputation: 5517

Use the unbind method:

var clickHandle = function(){
    $(this).unbind('click', clickHandle);
    callfunc();
};
var callfunc = function(){
    // do your stuff
    $('#imageid').click(clickHandle);// reinstall click handle
};
$('#imageid').click(clickHandle);

Upvotes: 0

philreed
philreed

Reputation: 2617

Another way would be to set a flag to indicate that the data is still being processed and unset the flag on completion:

var processing = false;

$("#imageid").click(function(e){
    if ( !processing )
    {
        //disable the click
        processing = true;
        $("idforanim").animate({left : "-=50px"},500,function(){callfunction1();})
    }
})

callfunction1(){
   //show the data
   //enable the click
   processing = false;
}

Upvotes: 5

Related Questions