how to prevent click queue build up, using toggle in jquery? tried using bind/unbind('click')

user177054 picture user177054 · Sep 22, 2009 · Viewed 13.3k times · Source

i want to disable the click handler when the toggle animation is showing so the animation won't build up because of multiple fast click. thanks

jquery script:

$("#button").click({
    $(this).unbind('click').next().toggle("slow",function(){$('#button').bind('click')});
});

html code

<div
   <a href='#' id='button'>Toggle</a>
   <div>
    test
   </div>
</div>

Answer

geowa4 picture geowa4 · Sep 22, 2009

First off, the way you are attaching events is broken. I don't know if that's just haste in asking the question or a real error in your code, but here's the correct way to set your handler:

$("#button").click(function(evt) { // <- you need to pass it a function!
    $(this).unbind('click').next()
       .toggle("slow",function(){$('#button').bind('click')});
});

But onto your problem. I think that you will benefit from using jQuery's one function. As soon as the click handler is called, it is removed as a click handler; therefore, it only executes once, for one click. To place the click handler back on after the animation, I think you got it right; re-bind it after the animation finishes.

function clickHandler(evt) {
    $(this).next().toggle("slow",
        function() {
            $('#button').bind('click', clickHandler);
        });
}

$("#button").one('click', clickHandler);

If using one is somehow too slow for you, the fastest way would be too add the javascript right on the href of the anchor. But you'll need to switch a global boolean variable when you are ready to execute again.

<a href="javascript:clickHandler(); return false;">...</a>

function clickHandler() {
    if( someBoolean ) {
        someBoolean = false;
        //do stuff
    }
    someBoolean = true;
}