Event Delegation Implementation in JavaScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Event Delegation runs in O(1) time and O(1) space, in JavaScript as in every other language.
- ✓The DOM supplies every piece natively. EventTarget.addEventListener attaches to any ancestor, Event.target names the node that was hit, Event.currentTarget names the node you bound to, and Element.closest(selectors) climbs from one to the other in a single call.
- ✓One review note comes up more than any other: closest() does not stop at the element you bound to.
- ✓The JavaScript trap: focus and blur do not bubble. Neither does scroll when it fires at an element rather than at the document, nor mouseenter and mouseleave, nor load and error on an image.
- ✓One listener is one closure and one entry in the target's listener list. A thousand rows add nothing, and blowing them away with innerHTML leaks nothing, because no detached node ever held a reference back into your code.
What Event Delegation actually is
Event Delegation in JavaScript: what you actually reach for
JavaScript implementation
const hall = document.querySelector("#seatmap");
const actions = {
"seat.hold": (el) => el.setAttribute("aria-pressed", "true"),
"seat.release": (el) => el.removeAttribute("aria-pressed"),
};
// One listener for the whole hall. Re-render every row from scratch and the
// wiring survives, because nothing was ever bound to a seat.
hall.addEventListener("click", (ev) => {
// closest() does not stop at hall: it climbs to <html>, so it can match a
// [data-action] wrapper that sits ABOVE the delegate. Re-check containment.
const seat = ev.target.closest("[data-action]");
if (!seat || !hall.contains(seat)) return;
const run = actions[seat.dataset.action];
if (typeof run !== "function") return;
ev.preventDefault();
run(seat, ev);
});
// focus does not bubble. focusin is its bubbling twin and is the only reason
// keyboard traversal of the seat grid works without per-seat listeners.
hall.addEventListener("focusin", (ev) => {
ev.target.closest("[data-action]")?.classList.add("is-focused");
});
// scroll fired at an element does not bubble either, so this one has to be
// caught on the way down. passive: the handler never calls preventDefault.
hall.addEventListener(
"scroll",
(ev) => {
if (ev.target instanceof Element) ev.target.dataset.scrolled = "1";
},
{ capture: true, passive: true },
);Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe JavaScript-specific trap
Performance in JavaScript, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which JavaScript type or library should I use for Event Delegation?
The DOM supplies every piece natively. EventTarget.addEventListener attaches to any ancestor, Event.target names the node that was hit, Event.currentTarget names the node you bound to, and Element.closest(selectors) climbs from one to the other in a single call. Node.contains bounds that climb. element.dataset reads data-* attributes, which is where the action name normally lives. The options argument takes capture, passive, once and signal, and passing an AbortSignal removes the listener later without you keeping a reference to the function itself.
What is the most common JavaScript mistake when implementing Event Delegation?
focus and blur do not bubble. Neither does scroll when it fires at an element rather than at the document, nor mouseenter and mouseleave, nor load and error on an image. So a delegate that is perfect for click returns nothing at all for the focus ring, and the failure is silent: no exception, no warning, just a handler that never runs and a feature that quietly does not exist. Two escapes: swap in the bubbling twins, focusin/focusout and mouseover/mouseout, or register with { capture: true }, since every event traverses the capture phase from the root down regardless of its bubbles flag.
How does Event Delegation actually perform in JavaScript?
One listener is one closure and one entry in the target's listener list. A thousand rows add nothing, and blowing them away with innerHTML leaks nothing, because no detached node ever held a reference back into your code. The cost moves to dispatch instead: closest() runs a selector match at each ancestor, so it is proportional to depth times the cost of the selector. Keep it a single attribute test, not a descendant combinator and not :has(). Mark scroll, wheel and touchstart listeners passive so the browser never stalls scrolling waiting to learn whether you call preventDefault(). Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Student discounts on developer tools are collected on Noizz, tool by tool.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.