What is event capturing?

Event capturing is the first phase of event propagation, where the event travels from window down through each ancestor towards the target; you listen during it by passing { capture: true } (or true) to addEventListener.

Propagation order

  1. Capture: window → document → html → body → ... → parent of target.
  2. Target: listeners on the target itself.
  3. Bubble: back up from the target to window.

So a capturing listener on an ancestor runs before any listener on the target, and a bubbling listener on the same ancestor runs after.

When capturing is useful

  • Intercepting events first: e.g. a global handler that blocks clicks while a modal is open, or logs every interaction before components see it.
  • Handling non-bubbling events at a parent: focus, blur, load and scroll do not bubble, but they do go through the capture phase. form.addEventListener("focus", fn, true) sees focus on every input.
  • Outside-click detection that should run before inner components stop propagation.

Removing a capturing listener

The capture flag is part of the listener's identity: removeEventListener(type, fn, true) must pass true again, or nothing is removed.

In React

React supports capture-phase handlers with the Capture suffix: onClickCapture, onFocusCapture.

Code example

js
1document.body.innerHTML = `<section id="outer"><div id="inner"><button id="btn">Click</button></div></section>`;
2const order = [];
3
4const outer = document.getElementById("outer");
5const inner = document.getElementById("inner");
6const btn = document.getElementById("btn");
7
8outer.addEventListener("click", () => order.push("outer capture"), { capture: true });
9inner.addEventListener("click", () => order.push("inner capture"), true);
10btn.addEventListener("click", () => order.push("button (target)"));
11inner.addEventListener("click", () => order.push("inner bubble"));
12outer.addEventListener("click", () => order.push("outer bubble"));
13
14btn.click();
15console.log(order);
16// ["outer capture", "inner capture", "button (target)", "inner bubble", "outer bubble"]
17
18// focus does not bubble, but capturing still sees it
19document.body.insertAdjacentHTML("beforeend", `<form id="f"><input id="a"><input id="b"></form>`);
20const seen = [];
21document.getElementById("f").addEventListener("focus", (e) => seen.push(e.target.id), true);
22document.getElementById("a").focus();
23document.getElementById("b").focus();
24console.log("focused inside form:", seen); // ["a", "b"]

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app