Lesson 5 of 8

Event delegation

Goal

One listener for items that get added and removed

01

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.

02

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
  1. Clicking "Delete" removes its item
  2. Clicking inside an item away from the button removes nothing
  3. It works for an item added after the listener was attached
  4. Removing two items in a row works with one listener
03

Hints

0/3
index.html
Preview
index.html100%
–/4

Press “Run and check” to grade your code.

4 checks listed under “Your task”.