JavaScript Reference ยท DOM: Events
Event bubbling and capturing
Understand the three event propagation phases: capture, target and bubble. See the order listeners run, eventPhase, the capture option and which events do not bubble.
When an event happens on an element, the browser does not just call that element's listeners. It walks the event through the DOM in three phases:
- Capture phase: from
windowdown throughdocumentand each ancestor to the parent of the target. - Target phase: the event reaches the target element itself.
- Bubble phase: back up from the target's parent to
documentandwindow, but only if the event bubbles.
Listeners added the normal way run in the bubble phase (and at the target). Listeners added with { capture: true } run in the capture phase, before any bubble listener.
parent.addEventListener("click", handler); // bubble phase parent.addEventListener("click", handler, { capture: true }); // capture phase
Try it
How propagation works
- The path is fixed when dispatching begins. Changing the DOM during dispatch does not change which ancestors will be visited.
- Capture listeners on ancestors run first. At the target itself, current browsers run its capture listeners before its non-capture ones (older browsers used the order of registration). Bubble listeners on ancestors run last.
event.eventPhaseis1(capturing),2(at target) or3(bubbling).event.bubblessays whether the bubble phase will happen.click,input,keydown,submitand most user events bubble.event.stopPropagation()ends the journey in either direction.
Usage notes
- Which events do not bubble:
focus,blur,load,unload,scroll(on elements),mouseenter,mouseleave,pointerenter,pointerleave, anderroron resources such as images. They still go through the capture phase, so a capture listener on an ancestor can hear them.focusin,focusout,mouseoverandmouseoutare bubbling alternatives. - Why use capture? It lets an ancestor see an event before the target does, which is useful for logging, global shortcuts or blocking an interaction (together with
stopPropagation()). - Bubbling is the basis of event delegation. One listener on a container can handle all its children.
- Custom events. Events made with
new Event()ornew CustomEvent()do not bubble unless you passbubbles: true. - Shadow DOM. Events only escape a shadow root if they are
composed. Most native UI events are. - Passing capture to
removeEventListener(). The capture flag is part of a listener's identity: remove it with the same value you added it with.
Browser support
Bubbling and capturing work in all browsers. The options-object form { capture: true } is supported in all current browsers.
Related
- event delegation โ using bubbling to your advantage
Event.stopPropagation()Event.targetandcurrentTargetEventTarget.addEventListener()- focus and blur events
- Lesson: Events