Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I unbind or prevent other click events from occurring while my function is running?

I have a carousel set up and I have click events tied to the navigation arrows. When they are clicked I use jQuery animate to animate in the elements of the next carousel slide, and due to the nature of the animations I use setTimeout() a few times.

I have one bug, where if I click on an arrow, and then quickly click the previous or next arrow, the animation will get confused due to the timeouts (which are necessary in this project) and render nothing on the screen. I've looked at this for awhile, and I figure that the best method might be to prevent the other arrows from being clickable until the current animation has completed.

Each arrow is controlled by click not on:('click', function() ... etc:

$("#arrow1").click(function() {...}

I've looked at

$("element").off("click");

But as they are not attached using the 'on' method I don't think this will work.

I want something like:

$("#arrow1").click(function() {
 $("#arrow2, #arrow3, #arrow4").off("click");
 // do my animations, then
 $("#arrow2, #arrow3, #arrow4").on("click");
}

But I haven't been able to get this to work yet.

like image 550
Rebecca O'Riordan Avatar asked Feb 07 '23 15:02

Rebecca O'Riordan


1 Answers

.off and .on do not work as you expect. The .click method and other event methods use the .on method behind the scenes for binding the handlers. When the .off method is called without any specific handlers it removes (and not temporary disables) all the bound handlers for a specific event. And calling .on without passing a handler has no effect.

In your case you can use a flag instead of manipulating event handlers which is also more efficient than (re)binding and removing the event handlers.

like image 125
undefined Avatar answered Feb 10 '23 15:02

undefined