Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Multiple Event Handlers - How to Cancel?

I have two functions bound to a click event at two different times (using jQuery). The order in which they are fired is significant. They are firing in the correct order. The problem is, when the first function returns false, the second function is still firing!

How can I properly cancel the event?

Example code:

$(document).click(function() {    alert('a');   return false; });  $(document).click(function() {   alert('b'); }); 

You will still see the "b" alert message when clicking the page. This is unacceptable!

like image 609
Josh Stodola Avatar asked Mar 16 '09 23:03

Josh Stodola


People also ask

How do I remove all event listeners?

To remove all event listeners from an element: Use the cloneNode() method to clone the element. Replace the original element with the clone. The cloneNode() method copies the node's attributes and their values, but doesn't copy the event listeners.

How do you stop event triggers?

@ezpura You can stop event propagation by calling e. stopPropagation(); or e. stopImmediatePropagation(); but that won't matter because $('button'). trigger('click'); creates two separate events.

Does jQuery remove unbind events?

jQuery unbind() MethodThe unbind() method removes event handlers from selected elements. This method can remove all or selected event handlers, or stop specified functions from running when the event occurs.

Can you have 2 event listeners?

You can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements.


1 Answers

Use the stopImmediatePropagation function of the jQuery event object.

Keeps the rest of the handlers from being executed. This method also stops the bubbling by calling event.stopPropagation().

$(document).click(function(event) {    alert('a');   event.stopImmediatePropagation();   return false; });  $(document).click(function() {   alert('b'); }); 
like image 83
Ken Browning Avatar answered Sep 22 '22 07:09

Ken Browning