On this page
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
- > Event Delegation & Cleanup with `AbortController`
- > Custom Events
Capture, Target & Bubble Phases
DOM events propagate in three phases:
- Capture (
window->document-> ... -> parent) - Target (the element that originated the event:
event.target) - Bubble (parent -> ... ->
document->window, for bubbling events likeclickandinput)
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
- tuts/web/dom Linked here; links to this page; shared tags: #dom, #platform, #web
- tuts/web/dom/nodes_and_elements Linked here; links to this page; shared tags: #dom, #platform, #web
- tuts/web/dom/shadow_dom_and_web_components Linked here; links to this page; shared tags: #dom, #platform, #web
- tuts/web/tutorials/vanilla_interactive_components Linked here; links to this page; shared tags: #platform, #web
- tuts/javascript/tutorials/functions_closures_and_this Linked here; links to this page; shared tags: #web
- tuts/html links to this page; shared tags: #web
- tuts/programming/paradigms/declarative_and_event_driven links to this page
- tuts/web shared tags: #platform, #web
- tuts/web/apis shared tags: #platform, #web
- tuts/web/apis/fetch_and_networking shared tags: #platform, #web