liveBook · Manning

Event delegation

As explained in Secrets of the JavaScript Ninja, Second Edition

An event-handling pattern in which a parent or ancestor element handles events for descendant elements by relying on propagation.

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

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains bubbling, ancestor placement, and the difference between event.target and this through DOM click examples.
Examples
Contrasts per-cell listeners with a table handler that colors clicked cells, and uses nested elements to show propagation.
What it assumes
Assumes familiarity with JavaScript functions and DOM elements, while introducing event.target and handler registration before delegation.
What you can do after
Apply it via addEventListener to handle descendant clicks at an ancestor while distinguishing the clicked target from the handler element.
How it connects
Connects event delegation to DOM event propagation, bubbling, capturing, addEventListener, and event.target.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.