The Capture and Bubble Phases
Understand how events travel through the DOM.
Two Trips Through the DOM
When you click an element, the event does not just fire on that element. It travels through the DOM tree in two phases: the capture phase (top down, from document to the target) and the bubble phase (bottom up, from the target back to document).
<div id="outer">
<button id="inner">Click</button>
</div>The Default: Bubbling
By default, addEventListener listens during the bubble phase. A click on the inner button fires its handler first, then the handler on its parent, then the grandparent, and so on up to document.
inner.addEventListener("click", () => console.log("inner"));
outer.addEventListener("click", () => console.log("outer"));
// Click inner -> logs: "inner" then "outer"All lessons in this course
- The Capture and Bubble Phases
- Event Delegation Pattern
- Dynamic Lists with Delegation
- Custom Events