liveBook · Manning

Event delegation

As explained in Vanilla Web

An event-handling technique that registers a listener on an ancestor and identifies relevant descendant interactions from the event.

When a container holds many repeated controls, attach one listener to the container instead of a listener to each child. This is event delegation: a descendant’s event reaches an ancestor through the bubble phase, where the listener checks which interaction matters. A list of 1,000 customers, for example, can use one listener on its <ul> rather than one on every <li>. section 6.2.13

Inside the listener, event.target is the node where the event originated; event.currentTarget is the container that owns the listener. A container listener receives clicks throughout that container, so inspect the target before running child-specific behavior. The two properties answer different questions: what was clicked, and where the shared listener was registered. section 6.2.13

<ul id="list">
  <li>Ana</li>
  <li>Bob</li>
  <li>Cara</li>
</ul>

<script>
  const list = document.getElementById("list");

  list.addEventListener("click", e => {
    console.log("target:", e.target); #1
    console.log("currentTarget:", e.currentTarget); #2
  });
</script>

This list logs both properties from a single container listener. Clicking a list item shows why the handler needs a target check before acting on a particular item. section 6.2.13

Use the default bubble phase for ordinary delegation. Capture is a separate choice when an ancestor must act before the target; stopPropagation() can halt the event’s remaining path. Delegation reduces listener overhead, but it does not remove the need to decide which descendant interactions the container should handle. section 6.2.13 section 6.4

How Vanilla Web covers it

How deep it goes
Explains bubbling and target/currentTarget with a logging example, but stops short of a complete child-interaction filter.
Examples
Uses a customer list with 1,000 items and a smaller <ul> example that logs click targets.
What it assumes
Assumes basic JavaScript and DOM elements while explaining the event phases and properties needed for delegation.
What you can do after
Apply it via addEventListener to handle repeated controls with one container listener while checking the event target.
How it connects
Connects event delegation to bubbling, capture, addEventListener, event.target, event.currentTarget, and propagation control.

Also explained in

Compare how 2 books explain event delegation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Vanilla Web. The section links point to the parts of the book it draws on.