tezvyn:

Event Bubbling vs. Capturing: The DOM's Two-Way Street

AI-drafted, machine-checkedSource: developer.mozilla.orgintermediate
Event Bubbling vs. Capturing: The DOM's Two-Way Street

An event fired on a nested element travels in two phases: first down from the root (capturing), then back up (bubbling). This is how all DOM events work, like clicks.

WHY IT EXISTS: To give developers flexible control over when an event handler runs. Should a click on a button also trigger the click handler on its parent container? The two-phase model lets you decide, preventing a free-for-all where event order is unpredictable.

THE MENTAL MODEL: Imagine dropping a stone into a set of nested bowls. The stone first passes down through each bowl's edge to reach the center (the capturing phase). It hits the target bowl. Then, the ripples spread back out from the center to the outermost bowl's edge (the bubbling phase).

HOW IT WORKS: When an event occurs on an element, the browser initiates a three-step process. First is the capturing phase, where the event travels from the root window down to the target element's parent. Second is the target phase, where the event fires on the element itself. Third is the bubbling phase, where the event travels back up from the target's parent to the window. By default, addEventListener('click', handler) listens for the bubbling phase. To listen during capture, you use the third argument: addEventListener('click', handler, true) or addEventListener('click', handler, { capture: true }).

WHEN TO USE IT: Use the default bubbling for most cases, like handling a specific button click. Use capturing for higher-level logic, like logging all clicks within a large component, intercepting an event before any child element can handle it, or implementing global shortcuts.

WHEN NOT TO USE IT: Don't use capturing just because you can; it's less common and can make code harder to reason about. Avoid overusing event.stopPropagation() to halt the event flow, as it can break other parts of the application that rely on listening for that event. Note that some events, like focus and blur, do not bubble at all.

ONE CANONICAL EXAMPLE: Consider a containing a <button>. If you add a click listener to both, which runs first? div.addEventListener('click', () => console.log('div clicked')); and button.addEventListener('click', () => console.log('button clicked'));. When you click the button, the console logs "button clicked", then "div clicked". This is bubbling in action. The event fires on the target (button) first, then bubbles up to its parent (div).

Read the original → developer.mozilla.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.