Imagine a table with hundreds of cells. Giving every cell the same click handler works, but repeats the registration hundreds of times. Event delegation puts one handler on the enclosing table instead. When a cell is clicked, the event bubbles up to the table, where that handler can respond. section 13.3.1
Two details make the pattern work:
- Register the handler on an ancestor of the intended targets, so their events can bubble to it. section 13.3.1
- Use event.target to identify the element where the event occurred. In an ordinary function handler, this refers to the element where the handler was registered—not necessarily the target. section 13.3 section 13.3.1
One table handler instead of many cell handlers
For clicks on table cells, a handler registered on the table can use event.target to find the clicked cell and change its background color. This replaces the alternative of registering the same click handler on every cell. section 13.3.1
Figure 13.15. With capturing, the event trickles down to the target element. With bubbling, the event bubbles up from the target element.
The propagation diagram shows why an ancestor handler can receive an event: after reaching its target, the event bubbles back up the DOM. section 13.3.1
