liveBook · Manning

Event propagation

As explained in Secrets of the JavaScript Ninja, Second Edition

Event propagation is the movement of an event through the DOM hierarchy from its target toward or from ancestor elements.

When a nested element is clicked, its event can reach handlers on ancestor elements too. Capturing carries the event down toward the target; bubbling carries it back up. section 13.3.1

Figure 13.16. First the event trickles down from the top, executing all event handlers in capturing mode. When the target element is reached, the event bubbles up to the top, executing all event handlers in bubbling mode.

The event travels down through capturing handlers, reaches its target, then travels upward through bubbling handlers. section 13.3.1

Propagation also makes it possible to handle descendant events at an ancestor:

  • In a handler, this refers to the element with that handler; event.target identifies the element where the event occurred. section 13.3.1
  • Event delegation uses one ancestor handler to respond to events from its descendants, avoiding identical handlers on every element. section 13.3.1

Delegate table-cell clicks

Instead of attaching a click handler to every cell to turn it yellow, attach one to the table and use event.target to identify the clicked cell. section 13.3.1

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains capturing, bubbling, handler context, and delegation, while noting that delegation requires an ancestor of the event targets.
Examples
Compares clicks on nested containers and delegates table-cell clicks to change cell backgrounds.
What you can do after
Apply DOM event listeners to delegate descendant clicks to an ancestor handler.
How it connects
Connects DOM events with event delegation and event.target.

Also explained in

Compare how 4 books explain event propagation →

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.