Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent other event handlers, from first handler, in jQuery

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.

like image 882
Saeed Neamati Avatar asked Nov 14 '11 07:11

Saeed Neamati


People also ask

Which method prevents all other listeners from being called for this particular event?

stopImmediatePropagation() Event Method The stopImmediatePropagation() method prevents other listeners of the same event from being called.

Which method prevent the event from bubbling up the DOM tree?

stopPropagation()Returns: undefined. Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

What is stopImmediatePropagation in jQuery?

stopImmediatePropagation() method stops the rest of the event handlers from being executed. This method also stops the event from bubbling up the DOM tree.

What is preventDefault jQuery?

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.


1 Answers

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.

like image 101
dcro Avatar answered Nov 10 '22 01:11

dcro