JavaScript Reference ยท DOM: Events
Event.stopPropagation() method
Reference for Event.stopPropagation() and stopImmediatePropagation(): stop an event from bubbling or capturing further, with examples and the pitfalls to avoid.
An event does not stop at the element where it happened. It travels through the DOM: down from window to the target (the capture phase), and then back up (the bubble phase). Calling event.stopPropagation() ends that journey. Listeners on the current element still finish, but no listener on any other element is called afterwards.
Its sibling stopImmediatePropagation() goes one step further: it also prevents the remaining listeners on the same element from running.
button.addEventListener("click", (event) => { event.stopPropagation(); });
Try it
Syntax
event.stopPropagation() event.stopImmediatePropagation()
Parameters
None.
Return value
undefined.
Usage notes
- It does not cancel the default action. A link still navigates after
stopPropagation(). UsepreventDefault()for that. The two are independent and often confused. - It works in both directions. Called during the capture phase, it prevents the event from ever reaching the target. Called at the target or while bubbling, it prevents it from moving up.
- Other listeners on the same element still run. Only
stopImmediatePropagation()blocks them, and only the ones added after the current listener. - It breaks event delegation. If a child stops propagation, a delegated listener on
documentor a container never hears the event. Analytics and "click outside to close" menus are common casualties. - Prefer alternatives. Instead of stopping the event, check
event.targetorevent.target.closest()in the parent, or let the event bubble and have the outer code ignore it when it does not apply. cancelBubble. The legacy propertyevent.cancelBubble = truedoes the same asstopPropagation(). Do not use it in new code.- Events that do not bubble.
focus,blur,loadand a few others do not bubble at all, so there is nothing to stop in the bubble phase (they still pass through the capture phase).
Browser support
stopPropagation() and stopImmediatePropagation() are supported in every browser.
Related
Event.preventDefault()โ cancel the default action instead- event bubbling and capturing โ the phases explained
- event delegation โ why stopping propagation can break it
Event.targetandcurrentTarget- Lesson: Events