Topic F2
Event bubbling and delegation
Events bubble up the DOM tree, and how one listener handles many elements.
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.
- moving now
- being checked
- passed / marked
- finished / the result
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 welltarget 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
A button inside an li inside a ul is clicked. Where does the event bubble?
What's the advantage of event delegation?
The user clicks an <svg> icon inside a button. event.target is…
0 of 3 answered.
Built on
Used in
No follow-up topics yet.