stopPropagation vs. stopImmediatePropagation
What's the difference between and ?event.stopPropagation()
event.stopImmediatePropagation()
What's the difference between and ?event.stopPropagation()
event.stopImmediatePropagation()
stopPropagation
will prevent any parent handlers from being executed will prevent any parent handlers and also any other handlers from executing stopImmediatePropagation
Quick example from the jquery documentation:
$("p").click(function(event) {
event.stopImmediatePropagation();
});
$("p").click(function(event) {
// This function won't be executed
$(this).css("background-color", "#f00");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>example</p>
Note that the order of the event binding is important here!
$("p").click(function(event) {
// This function will now trigger
$(this).css("background-color", "#f00");
});
$("p").click(function(event) {
event.stopImmediatePropagation();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>example</p>
Surprisingly, all other answers only say half the truth or are actually wrong!
e.stopImmediatePropagation()
stops any further handler from being called for this event, no exceptionse.stopPropagation()
is similar, but does still call all handlers for this phase on this element if not called alreadyWhat phase?
E.g. a click event will always first go all the way down the DOM (called “capture phase”), finally reach the origin of the event (“target phase”) and then bubble up again (“bubble phase”). And with you can register multiple handlers for both capture and bubble phase independently. (Target phase calls handlers of both types on the target without distinguishing.)addEventListener()
And this is what the other answers are incorrect about:
A fiddle and mozilla.org event phase explanation with demo.