Frontend Case Studies

Topic F2

Event bubbling and delegation

Events bubble up the DOM tree, and how one listener handles many elements.

8 min · beginner

Watch: the click starts at the button, then travels up through every part wrapped around it. One listener higher up is enough for every button.

documentbodyulli 1li 2buttonli 3buttonbutton
  • moving now
  • being checked
  • passed / marked
  • finished / the result
Step 1 of 6

A list of 3 items. Each li has its own event listener (the small box beside it).

An event starts at the clicked element, then bubbles up through every ancestor to the document.

An event's route

An event actually travels both ways. First down from the document to the target element (capture), then back up from the target to the document (bubble). Ordinary listeners (addEventListener("click", f)) run on the way up. The route is the target's list of ancestors, exactly the leaf-to-root path in a tree (Module 6).

Code, for programmersOne listener for every item
// instead of: items.forEach((li) => li.addEventListener("click", ...))
list.addEventListener("click", (e) => {
  const item = e.target.closest("li");     // walk up from the clicked element
  if (!item || !list.contains(item)) return;
  select(item.dataset.id);
});
// items added later work too: their clicks bubble through 'list' as well

target and currentTarget

  • event.target: the element actually clicked. It might be an icon or span inside the button, not the button itself.
  • event.currentTarget: the element the listener is attached to.
  • closest("li") walks up from the target until it finds a match, so a click on an icon inside an li still finds the li.

Stopping the journey

e.stopPropagation() stops the event bubbling any further. Use it sparingly: it also silences listeners above that you may need, such as analytics, closing a dropdown on an outside click, or another library's delegation. Often what you actually want is e.preventDefault(), which only cancels the browser's default action (following a link, submitting a form) without stopping the event.

Quiz

  1. A button inside an li inside a ul is clicked. Where does the event bubble?

  2. What's the advantage of event delegation?

  3. The user clicks an <svg> icon inside a button. event.target is…

0 of 3 answered.