DOM Events & Event Delegation — JavaScript interview guide
DOM Events & Event Delegation
Events travel down the DOM (capture) and back up (bubble). Event delegation uses bubbling to handle many children with one listener on the parent.
See it run
Press Play, or step with Next. Follow the arrows: anything that cannot be reached from a variable or root is free to go.
One click travels down (capture) and back up (bubble)
1const list = document.querySelector("#list");2▶document.body.addEventListener("click", () => {4console.log("body capture");5}, true);67list.addEventListener("click", (e) => {8const li = e.target.closest("li");9console.log("delegated", li.dataset.id);10});1112// the user clicks <li data-id="2">
What happens:Two listeners: one on <body> with capture = true (3rd argument), and one on the <ul>. There is NO listener on the <li> itself.
Explained simply
Capture, target, bubble
A click goes from window down to the target (capture phase), then back up to window (bubble phase). Listeners run in bubble phase by default.
stopPropagation stops the travel. preventDefault stops the browser default action (like following a link or submitting a form).
Event delegation
One listener on the list instead of one per item. It also works for items added later.
list.addEventListener("click", (e) => {
const item = e.target.closest("li[data-id]");
if (!item || !list.contains(item)) return;
console.log("clicked", item.dataset.id);
});Remember this
- e.target = element clicked; e.currentTarget = element with the listener.
- Some events do not bubble (focus, blur) — use focusin/focusout.
- React attaches its listeners at the root, which is delegation.
Interview questions
What is event delegation and why use it?
Handling events for many child elements with a single listener on a common ancestor, using bubbling. Fewer listeners, less memory, works for dynamic items.
Practice
- Build a todo list where delete buttons use delegation.
Keep learning
More in Browser & Practical JS