liveBook · Manning

Event capturing

As explained in Vanilla Web

The event-propagation stage in which an event travels down the DOM tree toward its target.

A click does not go straight to its target. During the capture phase, it travels from the window and document down through the target’s ancestors. It then reaches the target and bubbles back up. Choose capture when a listener must run on that downward path; listeners use the bubble phase by default. section 6.2.13

Register a capture listener

Use `document.addEventListener("click", handler, { capture: true })` to run a document listener as the event travels toward the clicked element. At the target, a capture listener runs before a bubble listener on that same element. section 6.2.13

const header = document.querySelector("header");
const p = document.querySelector("p");

// Capture phase: fires top-down, from document to the target
document.addEventListener("click", () =>  #1
  console.log("1 document capture"), { capture: true });
document.body.addEventListener("click", () =>
  console.log("2 body capture"), { capture: true });
header.addEventListener("click", () =>
  console.log("3 header capture"), { capture: true });
p.addEventListener("click", () =>
  console.log("4 p capture"), { capture: true });

// Bubble phase: fires bottom-up, from the target to document
p.addEventListener("click", () =>  #2
  console.log("5 p bubble"));
header.addEventListener("click", () =>
  console.log("6 header bubble"));
document.body.addEventListener("click", () =>
  console.log("7 body bubble"));
document.addEventListener("click", () =>
  console.log("8 document bubble"));

Follow the logged numbers to compare the downward capture path with the upward bubble path. A listener can interrupt propagation with `stopPropagation()`; `stopImmediatePropagation()` also skips remaining listeners on its element. section 6.2.13

How Vanilla Web covers it

How deep it goes
Traces capture, target, and bubble order with registered listeners, including their order at the target.
Examples
Logs a paragraph click across document, body, header, and paragraph listeners in both phases.
What it assumes
Builds on DOM elements and click listeners while defining the three event phases.
What you can do after
Apply it via addEventListener() with `{ capture: true }` to run a listener on the downward event path.
How it connects
Relates capturing to DOM event propagation, bubbling, addEventListener(), and propagation controls.

Also explained in

Compare how 3 books explain event capturing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Vanilla Web. The section links point to the parts of the book it draws on.