Lesson 6
Bubbling & delegation
Build a practical mental model for bubbling & delegation and use it in working JavaScript.
By the end, you will be able to…
- Explain bubbling & delegation in your own words
- Use bubbling & delegation in a small program
- Recognize and debug a common failure mode
Build the mental model
Events bubble upward from the element they occurred on through each ancestor. Delegation exploits this: attach one listener to a shared parent instead of one per child, then check event.target inside it.
Syntax and working example
Read the code from inputs to output. Predict what it prints, then run it and change one value.
Why this matters
Delegation handles elements added after the listener was attached (like new list items) without ever re-binding, and it uses far less memory than hundreds of individual listeners.
Real-world example
A comments section attaching one 'click' listener to the whole thread to catch 'delete' clicks on any comment, present or future.
Common mistakes
- Attaching a separate listener to every list item instead of one delegated listener on the parent
- Forgetting event.target might be a child of the element you actually care about (use closest())
- Not accounting for dynamically added elements when binding listeners individually
Try it yourself
Challenge
Write findClickedId(event) that returns the closest list item's id from a simulated event.
Knowledge check
What is the main benefit of event delegation?
Summary
Use event delegation — one listener on a shared ancestor, checking event.target — for lists and dynamic content.