Learning object 42 of 100
Event delegation explorer
Click items, icons inside items and rows added later, and see how one listener on the parent finds the right element with closest.
Loading…
What it shows
With event delegation, one listener on a parent handles events for all of its children, including children added later, because events bubble up to the parent. Inside the listener, event.target is the innermost element clicked, and event.target.closest(selector) climbs to the element you care about. data- attributes carry the ids and actions the handler needs.
Guided experiment
- In Delegated list, click an item's text and its badge. Does the handler find the same li?
- Click Add row, then click the new row.
- In Actions, use + and Remove and watch the cart object.
Predict
Why does a delegated listener work for rows added later?
Related
Lessons: Lesson 59: Event delegation
Projects: Project 9: Shopping Cart Price Calculator
Source: web/assets/js/objects/object-042.js in the companion repository.