On this page
  1. Events & Delegation
  2. Contents
  3. Capture, Target & Bubble Phases
  4. Event Delegation & Cleanup with AbortController
  5. Custom Events

Events & Delegation

Prev: Nodes & Elements | Up: dom | Next: Shadow DOM & Web Components
Rel: Functions, Closures & this, Vanilla Interactive Components
Ref: MDN Web Docs — EventTarget.addEventListener
Tags: #public #web #platform #dom #events


Contents


Capture, Target & Bubble Phases

DOM events propagate in three phases:

  1. Capture (window -> document -> ... -> parent)
  2. Target (the element that originated the event: event.target)
  3. Bubble (parent -> ... -> document -> window, for bubbling events like click and input)

Event Delegation & Cleanup with AbortController

Attach a single listener to a stable ancestor and match the clicked child via event.target.closest(...). Pass an AbortSignal to tear down groups of listeners cleanly:

const controller = new AbortController();

document.querySelector("#todo-list")?.addEventListener(
  "click",
  (event) => {
    const btn = event.target.closest("button[data-action]");
    if (!btn) return;
    console.log("Action:", btn.dataset.action);
  },
  { signal: controller.signal }
);

// Later: controller.abort(); // Removes all listeners bound to this signal

Custom Events

const ev = new CustomEvent("item:selected", {
  bubbles: true,
  composed: true, // Crosses Shadow DOM boundaries
  detail: { id: 42 },
});
element.dispatchEvent(ev);

Linked from

Related notes