Event Capturing, Targeting, and Bubbling

DOM events propagate through phases. During capture, the event travels from ancestors toward the target. The target phase occurs at the target. During bubbling, the event travels back outward through ancestors.

Event delegation uses bubbling to attach a listener to a stable ancestor rather than creating listeners for every child.

Event Propagation
Event Delegation
document.querySelector('#list').addEventListener('click', event => {
  const item = event.target.closest('[data-id]');
  if (!item) return;

  console.log(item.dataset.id);
});
💡 One listener on the list handles clicks from dynamically created child elements by examining the event target.
Key Takeaways
  • Events have capture and bubble phases.
  • Event delegation can reduce listener count.
  • event.target identifies the originating target while currentTarget identifies the listener's element.
Knowledge Check

What is a major benefit of event delegation?