Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

DOM Events & Event Delegation — JavaScript interview guide

17 / 23Browser & Practical JSHigh priorityMedium 25 min

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)

Step 1/9
events.js
1const list = document.querySelector("#list");
2
▶document.body.addEventListener("click", () => {
4 console.log("body capture");
5}, true);
6
7list.addEventListener("click", (e) => {
8 const li = e.target.closest("li");
9 console.log("delegated", li.dataset.id);
10});
11
12// the user clicks <li data-id="2">
DOM TREELISTENERSwindowdocument<body><ul id="list"><li data-id="2">log("body capture")capture listener on <body>log("delegated", id)click listener on <ul>
event passing through event target listener running
Console
nothing printed yet

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

  1. Build a todo list where delete buttons use delegation.

Keep learning