Event Bubbling, Capturing & Event Flow

Difficulty: Intermediate

Question

Explain event bubbling and capturing in JavaScript. How does the event flow work in the DOM?

Answer

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

1. Capturing Phase (top-down): Event travels from window down to the target element 2. Target Phase: Event reaches the target element 3. Bubbling Phase (bottom-up): Event bubbles up from the target back to window

By default, event listeners fire during the bubbling phase. You can listen during the capturing phase by passing { capture: true } as the third argument to addEventListener.

Key methods: - event.stopPropagation(): Stops event from propagating further - event.stopImmediatePropagation(): Stops propagation AND prevents other handlers on same element - event.preventDefault(): Prevents default browser behavior (not related to propagation)

Code examples

Bubbling Demonstration

// HTML: <div id="outer"><div id="inner"><button id="btn">Click</button></div></div>

document.getElementById("outer").addEventListener("click", () => {
  console.log("Outer - Bubble");
});

document.getElementById("inner").addEventListener("click", () => {
  console.log("Inner - Bubble");
});

document.getElementById("btn").addEventListener("click", () => {
  console.log("Button - Bubble");
});

// Clicking the button logs:
// Button - Bubble
// Inner - Bubble
// Outer - Bubble

The event starts at the button (target) and bubbles up through parent elements.

Capturing Phase & stopPropagation

document.getElementById("outer").addEventListener("click", () => {
  console.log("Outer - Capture");
}, true); // capture phase

document.getElementById("inner").addEventListener("click", (e) => {
  console.log("Inner - Capture");
  e.stopPropagation(); // stops further propagation
}, true);

document.getElementById("btn").addEventListener("click", () => {
  console.log("Button"); // never fires!
});

// Clicking the button logs:
// Outer - Capture
// Inner - Capture
// (stops here due to stopPropagation)

stopPropagation prevents the event from reaching further elements in both capturing and bubbling.

Key points

Concepts covered

Event Bubbling, Event Capturing, stopPropagation, Event Flow