Is there any difference between calling event.stopImmediatePropagation()
and return false
inside an event handler ?
preventDefault() prevents the default browser behavior for a given element. stopPropagation() stops an event from bubbling or propagating up the DOM tree. Whereas, return false is a combination of both preventDefault() and stopPropagation() .
e. preventDefault() will prevent the default event from occuring, e. stopPropagation() will prevent the event from bubbling up and return false will do both. Note that this behaviour differs from normal (non-jQuery) event handlers, in which, notably, return false does not stop the event from bubbling up.
So the difference here is that since the div is the parent of the button that got clicked, stopPropagation() makes sure that 3 is never alerted, whereas stopImmediatePropagation() makes sure that not even other event listeners registered on the button itself, i.e. 2 , are executed.
stopImmediatePropagation() The stopImmediatePropagation() method of the Event interface prevents other listeners of the same event from being called. If several listeners are attached to the same element for the same event type, they are called in the order in which they were added.
Yes they are different.
return false
is basically the same as calling both, event.stopPropagation()
and event.preventDefault()
.
Whereas event.stopImmediatePropagation()
is the same as event.stopPropagation()
plus preventing other registered event handlers on the same element to be executed. So it does not prevent the default action for an event, such as following a clicked link.
In short:
stop | prevent | prevent "same element" bubbling | default action | event handlers return false Yes Yes No preventDefault No Yes No stopPropagation Yes No No stopImmediatePropagation Yes No Yes
return false
also works in "normal" JavaScript event handlers
event.stopPropagation()
and event.preventDefault()
also work in "normal" JavaScript event handlers (in a W3C compatible browser), whereas event.stopImmediatePropagation()
is an extension from jQuery (update: apparently it is part of the DOM Level 3 Events specification).
Note: return false
does not prevent the event from bubbling up in "normal" (non-jQuery) event handlers (see this answer)(but still prevents the default action).
Maybe worth reading:
Returning false
will stop event bubbling, but other bound events will fire. However stopImmediatePropagation
prevents other bound events from firing and stops bubbling.
Code Example of this on jsfiddle.
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