Click a nested element and its parent’s click handler may run too. The event has not happened twice: it is traveling through the DOM. During event bubbling, dispatch moves from the target element up through its ancestors. section 13.3.1 section 13.4
Follow the two phases to predict handler order:
- Capturing travels from the top of the DOM tree down to the target. Bubbling then travels back up. section 13.3.1
- With click handlers on an inner element, its outer container, and document, default registration runs them in that order: inner, outer, document. section 13.3.1
- Pass true as the third argument to addEventListener to register a capturing handler. Pass false, or omit it, for bubbling. section 13.3.1
A bubbling handler needs to distinguish where the event began from where it is being handled. In a regular function handler, event.target identifies the element where the event occurred; this refers to the element where that handler was registered. For a click on an inner element, an outer element’s handler can therefore see the inner element as event.target and the outer element as this. section 13.3 section 13.3.1
Listing 13.8. Capturing versus bubbling
const outerContainer = document.getElementById("outerContainer");
const innerContainer = document.getElementById("innerContainer");
document.addEventListener("click", () => {
report("Document click");
}); #A
outerContainer.addEventListener("click", () => {
report("Outer container click");
}, true); #B
innerContainer.addEventListener("click", () => {
report("Inner container click");
}, false); #C
Compare the registrations: the outer container uses capturing, while the inner container and document use bubbling. Phase selection changes when each handler runs. section 13.3.1
This propagation behavior is useful when considering event delegation: handling events through the DOM hierarchy can support simpler, less memory-intensive code. First check the phase and the event target before assuming that a handler ran on the element that was clicked. section 13.0 section 13.3.1


