If you attach two or more event handlers to an HTML element, they would be executed one after the other. However, if you want to stop the subsequent event handlers, based on a condition checked in the first handler, then what you should do?
For example:
<div id='target'> </div> <p id='result'> </p>
I'd like to cancel the second handler, if the first handler is cancelled.
$(function() { var target = $('#target'), result = $('#result'); target.click(function(e) { result.append('first handler<br />'); // Here I want to cancel all subsequent event handlers }); target.click(function(e) { result.append('second handler<br />'); }); });
You can see the fiddle here.
PS: I know that e.preventDefault()
prevents the default action of the HTML element (for example, preventing an HTTP GET request being sent because of the click on a link), and e.preventPropagation()
causes the event from being propagated to its parent elements in the DOM tree. I also know that it's possible to use a middle variable, set it to true in first handler, and check it in subsequent handlers. But I want to see if there is a more neat, sophisticated solution to this problem or not.
stopImmediatePropagation() Event Method The stopImmediatePropagation() method prevents other listeners of the same event from being called.
stopPropagation()Returns: undefined. Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
stopImmediatePropagation() method stops the rest of the event handlers from being executed. This method also stops the event from bubbling up the DOM tree.
preventDefault() method stops the default action of an element from happening. For example: Prevent a submit button from submitting a form. Prevent a link from following the URL.
See event.stopImmediatePropagation()
- http://api.jquery.com/event.stopImmediatePropagation/
According to the jQuery API docs, this method:
Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.
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