Lesson 5 of 8
Event delegation
- 14 min
- 4 checks
- 3 hints
- Go to task
Goal
One listener for items that get added and removed
Explanation
If you attach a listener to every delete button, what happens to the buttons added after that? Nothing happens when you click them, because they didn't exist when you attached the listeners.
The fix relies on the fact that an event bubbles up from the clicked element to the elements that contain it. So you attach a single listener to the container, then check inside it which element was actually clicked.
The expression event.target.closest('.del') returns the clicked element itself if it matches the selector, or its nearest ancestor that matches. If it finds nothing, it returns null.
Your task
Attach a single listener to #list that removes an item when its delete button is clicked, and that also works for items added later.
Checks
4 checks- Clicking "Delete" removes its item
- Clicking inside an item away from the button removes nothing
- It works for an item added after the listener was attached
- Removing two items in a row works with one listener