Bubbling & Capturing

bubbling capturing
bubbling capturing

In JavaScript event handling within the DOM, bubbling and capturing describe how events propagate through nested elements.

💡 Event Propagation Phases

When an event occurs on an element, it goes through three phases:

  • Capturing phase: Event travels down from the root to the target element.
  • Target phase: Event reaches the actual target element.
  • Bubbling phase: Event bubbles up from the target back up to the root.
Capturing vs. Bubbling
CapturingBubbling
Event moves from ancestor down to targetEvent moves from target up to ancestors
Less commonly usedDefault phase for event listeners
Listener’s capture option is trueListener’s capture option is false or omitted
Useful for intercepting events before targetUseful for handling events after target

💡 Adding Event Listeners with Capturing or Bubbling

Use addEventListener third parameter to specify phase:

  • element.addEventListener('click', handler, true) – capturing phase
  • element.addEventListener('click', handler, false) or omit – bubbling phase

📌 Deep Dive: Event Listener Phases

JAVASCRIPT
const outer = document.getElementById('outer');
const inner = document.getElementById('inner');

outer.addEventListener('click', () => console.log('Outer bubbled'), false);
outer.addEventListener('click', () => console.log('Outer captured'), true);

inner.addEventListener('click', () => console.log('Inner bubbled'), false);
inner.addEventListener('click', () => console.log('Inner captured'), true);
Output when clicking inner
Outer captured
Inner captured
Inner bubbled
Outer bubbled

⚠️ Remember:

The default event listener phase is bubbling. Use {capture: true} explicitly to listen during capturing.

Stopping propagation can control the flow:

  • event.stopPropagation() stops event from moving to other listeners in the same phase and next phases.
  • event.stopImmediatePropagation() also prevents other listeners on the same element from running.

💡 Practical Use Cases

  • Capturing: Useful for intercepting events before they reach deeper elements (e.g., global shortcuts).
  • Bubbling: Commonly used for event delegation to handle many child elements from a single parent listener.