How events travel
When you interact with an element, the event travels through phases. In the bubbling phase it rises from the target up through its ancestors. This is what makes delegation possible.
The pattern
Event delegation attaches a single listener to a common ancestor instead of one per child. When an event bubbles up, the handler inspects event target to decide what was clicked.
- Attach one listener to a list, not one per list item.
- Match the target with closest to find the relevant element.
- Ignore events that did not originate from a target you care about.
Why it helps
- Fewer listeners means less memory and setup work.
- It handles dynamic children added later for free, since the parent already listens.
Be careful with events that do not bubble, like focus, where you may need the capture phase instead.
Key idea
One listener on a parent handles many children through bubbling, saving memory and covering elements added later.