How do I "rebind" the click event after unbind('click')?

Ben picture Ben · Apr 7, 2010 · Viewed 17.3k times · Source

I have an anchor tag <a class="next">next</a> made into a "button". Sometimes, this tag needs to be hidden if there is nothing new to show. All works fine if I simply hide the button with .hide() and re-display it with .show(). But I wanted to uses .fadeIn() and .fadeOut() instead.

The problem I'm having is that if the user clicks on the button during the fadeOut animation, it can cause problems with the logic I have running the show. The solution I found was to unbind the click event from the button after the original click function begins, and then re-bind it after the animation is complete.

$('a.next').click(function() {
    $(this).unbind('click');
    ...
    // calls some functions, one of which fades out the a.next if needed
    ...
   $(this).bind('click');
}

the last part of the above example does not work. The click event is not actually re-bound to the anchor. does anyone know the correct way to accomplish this?

I'm a self-taught jquery guy, so some of the higher level things like unbind() and bind() are over my head, and the jquery documentation isn't really simple enough for me to understand.

Answer

nickf picture nickf · Apr 7, 2010

I would just add a check to see if it's animating first:

$('a.next').click(function() {
    if (!$(this).is(":animated")) {
        // do stuff
    }
});