Track 02 · Lesson 1 of 17Inside the browser

Track 02 · Inside the browser

Events and bubbling

Lesson 1 of 17· 7 min

When you click something, the event doesn't just happen on that element. It travels down the tree to the target, then bubbles back up through every ancestor, and each one can react.

Click and watch it travel

These are real listeners on real elements

<section>
<div class="card">

Event log

  1. Click the button, then the empty space inside the card.
// One listener on each element
section.addEventListener("click", log);
card.addEventListener("click", log);
button.addEventListener("click", log);

Three phases, one click#

Every event that bubbles goes through three phases:

  1. Capture: from the window down through each ancestor towards the target. Listeners only hear this phase if you ask, with { capture: true }.
  2. Target: the element that was actually clicked.
  3. Bubble: back up through every ancestor, from the closest to the furthest. This is where almost all listeners live.

Two properties tell you where you are. event.target is what was actually clicked. event.currentTarget is the element whose listener is running right now. In the demo, the card's listener sees the button as its target.

Stopping it#

event.stopPropagation() ends the journey: no element further along hears the event. Use it sparingly. Analytics scripts, dropdowns that close when you click elsewhere, and your own code higher up the tree may all be relying on that click reaching them.

Check yourself

You click a button inside a card inside a section. In what order do bubbling listeners run?