Track 02 · Lesson 5 of 17Inside the browser
- 01Events and bubbling
- 02What fires when you click or type
- 03Keyboard, input and focus events
- 04Default actions and preventDefault()
- 05Event delegation
- 06Listener options and cleanup
- 07Custom events
- 08Debounce and throttle
- 09Events in React
- 10The event loop
- 11Don't block the main thread
- 12The rendering pipeline
- 13Core Web Vitals
- 14HTTP caching
- 15Responsive design
- 16SEO basics
- 17Service workers and offline
Event delegation
Lesson 5 of 17· 6 min
Instead of a listener on every list item, put one listener on the list and check event.target. It uses less memory, and, crucially, it works for items added later. Add items in both versions and click them.
The bug, then the fix
Add a few items, then click the new ones
0
listeners attached
0
items that don’t respond
- Click the tasks, add a few, then click the new ones.
// Runs once, on page load
document.querySelectorAll("#todos li").forEach((li) => {
li.addEventListener("click", () => li.classList.toggle("done"));
li.querySelector(".del").addEventListener("click", (e) => {
e.stopPropagation();
li.remove();
});
});
// Items added later never get these listeners.Why the first version breaks#
The setup code runs once, when the page loads, and gives each existing item its own listeners. Items added later were never there when that code ran, so they never get any. It's one of the most common bugs in plain JavaScript, and it hides well: everything works until the list changes.
How delegation works#
Clicks bubble, so a click on any item, or on anything inside an item, eventually reaches the list. One listener there can work out which item was hit:
event.targetis the exact element clicked, which might be a span or icon inside the item.event.target.closest("li")walks up from there to the nearest list item.- Checking
closest(".del")first tells you whether the click landed on the delete button.
Check yourself