What is event bubbling and capturing in JavaScript

· Category: JavaScript

Short answer

Event propagation has three phases: capture (down the DOM tree), target (the element itself), and bubble (up the DOM tree). Most events bubble by default.

How it works

  1. Capture phase: The event travels from the document root to the target element.
  2. Target phase: The event reaches the element that triggered it.
  3. Bubble phase: The event travels back up from the target to the root.

Handlers attached without a third argument listen during the bubble phase. Passing true as the third argument listens during capture.

Example

document.querySelector("#parent").addEventListener("click", () => {
  console.log("parent");
});
document.querySelector("#child").addEventListener("click", (e) => {
  console.log("child");
  // e.stopPropagation(); // prevents bubbling to parent
});
// Clicking child logs: child, then parent (bubble phase)

Why it matters

Understanding propagation lets you implement event delegation, optimize performance by attaching fewer listeners, and avoid unintended side effects from nested handlers.