What is event bubbling?

Event bubbling is the phase where an event, after reaching its target element, travels back up through each ancestor (parent, grandparent, up to document and window), triggering their listeners for the same event.

The full journey of an event

  1. Capturing phase: from window down to the target's parent.
  2. Target phase: on the element that was actually clicked.
  3. Bubbling phase: back up from the target to window.

Listeners added normally (addEventListener(type, fn)) run in the bubbling phase.

target vs currentTarget

  • event.target: the element where the event started (the innermost clicked element).
  • event.currentTarget: the element whose listener is running right now.

Stopping it

  • event.stopPropagation(): stops the event from reaching further ancestors.
  • event.stopImmediatePropagation(): also stops other listeners on the same element. Use these sparingly; they can break analytics, outside-click handlers for dropdowns, and delegated listeners elsewhere.

Not every event bubbles

focus, blur, mouseenter, mouseleave, load and scroll (on elements) do not bubble. Bubbling alternatives exist: focusin/focusout, mouseover/mouseout. Check event.bubbles.

Why it is useful

Bubbling makes event delegation possible: one listener on a parent handles events for all its children, including ones added later.

Code example

js
1document.body.innerHTML = `
2 <div id="card" style="padding:16px;border:1px solid #ccc">
3 Card
4 <button id="like">Like <span id="icon">♥</span></button>
5 </div>`;
6
7const log = [];
8for (const id of ["card", "like", "icon"]) {
9 document.getElementById(id).addEventListener("click", (e) => {
10 log.push(`${e.currentTarget.id} (target: ${e.target.id})`);
11 });
12}
13document.body.addEventListener("click", () => log.push("body"));
14
15document.getElementById("icon").click(); // simulate a click on the innermost element
16console.log(log);
17// ["icon (target: icon)", "like (target: icon)", "card (target: icon)", "body"]
18
19// Stop the event from reaching ancestors
20log.length = 0;
21document.getElementById("like").addEventListener("click", (e) => e.stopPropagation());
22document.getElementById("icon").click();
23console.log(log); // ["icon (target: icon)", "like (target: icon)"] - card and body never ran
24
25console.log(new Event("focus").bubbles, new MouseEvent("click", { bubbles: true }).bubbles); // false true

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