JavaScript AcademyProfessional Engineering
Level 3 · Interactive Web ApplicationsModule 12: Events and InteractionLesson 58 of 150About 45 minutes

Lesson 58: Event bubbling and capturing

01Opening question

You click a button inside a card inside a page. Did you click the button, the card or the page?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

One click on the button runs the button's listener and then the div's listener: the event bubbles up through its ancestors.

for (const id of ["outer", "inner"]) {
  document.getElementById(id).addEventListener("click", () => console.log("click on", id));
}
document.getElementById("inner").click();

03Objective and prerequisites

Learning objective: Trace how an event travels through capture, target and bubble phases, and control it with stopPropagation and the capture option.

You need: Lesson 57: Event objects

Skills practised: Events, Bubbling and capturing.

04Explanation

When you click an element, the event does not stay there. It bubbles up to the parent, then the grandparent, all the way to document and window.

So a listener on a container also hears clicks on everything inside it. That is useful, but it can also trigger handlers you did not expect.

event.stopPropagation() stops the event from travelling any further up. Use it sparingly, because other code may rely on hearing the event.

Before bubbling there is a capture phase that travels down from the window to the target. Listeners added with { capture: true } run during that trip down.

05Definitions

Event propagation
The path an event travels through the DOM: down in the capture phase and up in the bubble phase.
Bubbling
The phase in which an event travels from the target up through its ancestors.
Capturing
The phase in which an event travels from the window down to the target, before bubbling.
stopPropagation
A method that stops an event from reaching any further elements.
eventPhase
A number showing the current phase: 1 capture, 2 at target, 3 bubble.

Open the full glossary

06Visual learning object

Event propagation visualizer. Click nested boxes and watch the event travel down in capture, reach the target and bubble back up.

Loading the interactive object…

Open the full Event propagation visualizer page with its guided experiment.

07Examples

ex-058-01Bubbling order Browser page (sandboxed preview)

A click on the innermost element is heard by every ancestor, inside out.

for (const id of ["page", "card", "like"]) {
  document.getElementById(id).addEventListener("click", () => console.log(id));
}
document.getElementById("like").click();
Sample input
None
Expected output
like card page
Common mistake
Expecting the order to follow when the listeners were added; bubbling order follows the tree.
Try this
Click the card instead and predict the output.
Source
examples/ex-058-01-bubble-order.js

ex-058-02Capture runs first Browser page (sandboxed preview)

{ capture: true } listeners run on the way down, before bubble listeners.

const outer = document.getElementById("outer");
const btn = document.getElementById("btn");
outer.addEventListener("click", (e) => console.log("outer bubble", e.eventPhase));
outer.addEventListener("click", (e) => console.log("outer capture", e.eventPhase), { capture: true });
btn.addEventListener("click", (e) => console.log("button", e.eventPhase));
btn.click();
Sample input
None
Expected output
outer capture 1 button 2 outer bubble 3
Common mistake
Thinking capture: true changes the order on the target itself; it only matters for ancestors.
Try this
Add a capture listener on document and predict where it appears.
Source
examples/ex-058-02-capture-first.js

ex-058-03stopPropagation Browser page (sandboxed preview)

Stopping propagation keeps a click inside a dialog from reaching the backdrop.

let open = true;
document.getElementById("backdrop").addEventListener("click", () => {
  open = false;
  console.log("backdrop: close dialog");
});
document.getElementById("dialog").addEventListener("click", (e) => {
  e.stopPropagation();
  console.log("dialog: keep open");
});
document.getElementById("ok").click();
console.log("open:", open);
document.getElementById("backdrop").click();
console.log("open:", open);
Sample input
None
Expected output
dialog: keep open open: true backdrop: close dialog open: false
Common mistake
Calling stopPropagation in a global handler and breaking other features that listen on document.
Try this
Instead of stopPropagation, check e.target === e.currentTarget on the backdrop.
Source
examples/ex-058-03-stop.js

ex-058-04Events that do not bubble Browser page (sandboxed preview)

focus does not bubble; focusin does. Synthetic events need bubbles: true.

const form = document.getElementById("form");
const email = document.getElementById("email");
form.addEventListener("focus", () => console.log("form heard focus"));
form.addEventListener("focusin", () => console.log("form heard focusin"));
form.addEventListener("change", () => console.log("form heard change"));
email.dispatchEvent(new FocusEvent("focus"));
email.dispatchEvent(new FocusEvent("focusin", { bubbles: true }));
email.dispatchEvent(new Event("change"));
email.dispatchEvent(new Event("change", { bubbles: true }));
Sample input
None
Expected output
form heard focusin form heard change
Common mistake
Dispatching new Event("change") in a test and wondering why the form's listener never runs.
Try this
Log event.bubbles for each event.
Source
examples/ex-058-04-non-bubbling.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

The row also opens

Stop a click from reaching the row.

const actions = [];
document.getElementById("row").addEventListener("click", () => actions.push("open"));
document.getElementById("archive").addEventListener("click", () => actions.push("archive"));
document.getElementById("archive").click();
console.log(actions.join(", "));

Trace the path

Record capture and bubble order.

const path = [];
for (const id of ["a", "b", "c"]) {
  const el = document.getElementById(id);
  // TODO: add a capture listener that pushes id + ":down"
  // TODO: add a bubble listener that pushes id + ":up"
}
document.getElementById("c").click();
console.log(path.join(" "));

Close when clicking outside

Use target checks instead of stopPropagation.

// Write onOverlayClick(event): set closed = true only when the click
// landed on the overlay itself, not on the panel or anything inside it.
let closed = false;

09Prediction

Commit to an answer first, then run the real code to compare.

// HTML: <div id="o"><p id="i">Hi</p></div>
const o = document.getElementById("o");
const i = document.getElementById("i");
i.addEventListener("click", (e) => { e.stopPropagation(); console.log("p"); });
o.addEventListener("click", () => console.log("div"), { capture: true });
i.click();

What is printed?

10Debugging investigation

The menu closes as soon as it opens

Clicking Options should open the menu, and clicking anywhere else should close it. The menu never appears.

const menu = document.getElementById("menu");
document.getElementById("open").addEventListener("click", () => {
  menu.hidden = false;
});
document.addEventListener("click", () => {
  menu.hidden = true;
});
document.getElementById("open").click();
console.log("menu open: " + !menu.hidden);

More cases in the Debugging Detective Laboratory

11Practical scenario

Dropdowns that close when you click elsewhere

Most design systems close an open dropdown when you click anywhere else. They listen for clicks on the document and check whether event.target is inside the dropdown with contains(). That works because every click bubbles up to the document.

const inside = (path, menu) => path.includes(menu);
console.log(inside(["item", "menu", "body"], "menu"), inside(["heading", "body"], "menu"));

12Knowledge check

1. What is bubbling?

  • The event travelling from the target up through its ancestors
  • The event travelling down to the target
  • An event repeating
  • Events queued for later

2. Listeners on a section, an article inside it and a button inside that log their tag. The button is clicked. What is the order?

  • SECTION ARTICLE BUTTON
  • BUTTON ARTICLE SECTION
  • BUTTON only
  • ARTICLE BUTTON SECTION

3. How do you make a listener run during the capture phase?

  • Call event.capture()
  • Pass { capture: true } to addEventListener
  • Use onclickcapture
  • Add it to window

4. Why does the form's listener never run in this test?

form.addEventListener("input", log);
field.dispatchEvent(new Event("input"));
  • The event was created without bubbles: true
  • forms cannot hear input
  • dispatchEvent needs a second argument
  • input must be lower case

5. What does stopPropagation do?

  • Cancels the default action
  • Stops the event from reaching further elements
  • Removes all listeners
  • Stops the page from scrolling

6. To close a modal when its backdrop is clicked, which is more robust?

  • stopPropagation in every element inside the modal
  • Check event.target === event.currentTarget in the backdrop listener
  • Add listeners to every child
  • Use a timer

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • The row also opens: Prints archive; Clicking the row still opens
  • Trace the path: Prints the full path; Six steps recorded
  • Close when clicking outside: Prints false then true; No stopPropagation

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-03-interactive-web-applications/module-12-events-and-interaction/lesson-058-event-bubbling-and-capturing/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • Events travel down (capture), reach the target, then travel up (bubble).
  • Ancestors hear events from their descendants.
  • { capture: true } runs a listener on the way down.
  • stopPropagation stops the journey; prefer target checks where you can.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation event bubbling and capturing
Context: I am learning event bubbling and capturing in JavaScript.
Task: Explain capture, target and bubble phases with nested elements and logged listeners.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction event bubbling and capturing drill
Context: I have practised event bubbling and capturing.
Task: Give me six nested-element programs and ask which listeners run and in what order.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging event bubbling and capturing bug
Context: A click on a button inside a table row also opens the row.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation event bubbling and capturing practice
Context: I finished the event bubbling and capturing exercises.
Task: Create three propagation exercises with exact expected orders.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review event bubbling and capturing review
Context: Here is my code that uses event bubbling and capturing.
Task: Review my code for stopPropagation calls that might break other features.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.