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!
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.
@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.
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.
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.
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'); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With