jim dif
jim dif

Reputation: 641

Event handlers jQuery revisited

I have this code below:

$("#radar_play").click(function(){
console.log(this);
$(this).unbind('click');
$(this).bind('click');
....
.....
.....

}

Then in the <body> tag I have this button below

<button id="radar_play'">PLAY ANIMATION</button>

To me it looks like I am removing the click event(which does work)then re-attaching it.

But the click event never gets bound again. Anyone know why?

Upvotes: 0

Views: 55

Answers (2)

You need to specify a handler when re-binding, you could name your closure and use it as follows:

$("#radar_play").click(function click_handler(){
   //Perform the onclick logic
   $(this).blabla...
   $(this).unbind('click');
   ....
   //now we want to bind again
   $(this).bind('click', click_handler);
});

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55740

When you are rebinding the click event you need to give it a handler too.. Otherwise the event will not be acted on..

 $(this).unbind('click');
    $(this).bind('click', function() {

        // What you want to do

    });

OR

$(this).unbind('click').bind('click', function() {

    // What you want to do
});

Also note that frequent bind and unbind is an antipattern .. You need to avoid it if you can

Upvotes: 2

Related Questions