Event Propagation and Delegation
When you click a button inside a table row inside a list, you didn't only click the button: you also clicked the row, the list and the whole page. Event propagation is the process by which an event travels through the DOM tree, so that listeners on every ancestor get a chance to react. It happens in three phases (capture, target, bubble), and it makes possible one of the most useful techniques in front-end code: event delegation, where one listener on a parent handles events for all of its children, including ones added later.
In One Minute
- An event travels down from
windowto the target (capture phase), hits the target, then travels back up (bubble phase). - Listeners run in the bubble phase by default;
{ capture: true }runs them on the way down. event.stopPropagation()stops the event from reaching further elements.preventDefault()is different: it cancels the browser's default action.- Event delegation: put one listener on a container and use
event.target.closest(selector)to find which child was used. - A few events don't bubble (
focus,blur,mouseenter,mouseleave); use their bubbling versions (focusin,focusout,pointerover) for delegation.
The Three Phases
<div id="outer"><p id="middle"><button id="btn">Pay</button></p></div>
<script>
const log = (label) => (event) => console.log(`${label} (phase ${event.eventPhase})`);
for (const id of ["outer", "middle", "btn"]) {
const el = document.getElementById(id);
el.addEventListener("click", log(`${id} capture`), { capture: true });
el.addEventListener("click", log(`${id} bubble`));
}
</script>outer capture (phase 1)
middle capture (phase 1)
btn capture (phase 2)
btn bubble (phase 2)
middle bubble (phase 3)
outer bubble (phase 3)Explanation: the click starts at the top and travels down to the button (capture listeners run: outer, then middle), reaches the target (phase 2, where both kinds of listener on the button run in the order they were added), then travels back up (bubble listeners: middle, then outer). The full path also includes window, document, <html> and <body>.
| Phase | eventPhase | Direction | Listeners that run |
|---|---|---|---|
| Capture | 1 | window down to the target's parent | Those added with { capture: true } |
| Target | 2 | At the target itself | All listeners on the target |
| Bubble | 3 | Target's parent up to window | Normal listeners (the default) |
stopPropagation vs preventDefault
These two are often confused. They do completely different things:
| Method | Stops |
|---|---|
event.stopPropagation() | The event from traveling to further elements (other listeners on the same element still run) |
event.stopImmediatePropagation() | Further elements and the remaining listeners on this element |
event.preventDefault() | The browser's default action (navigation, submission, checkbox toggle). The event keeps traveling. |
<div id="card"><a id="link" href="https://example.com">Details</a></div>
<script>
document.querySelector("#card").addEventListener("click", () => console.log("card clicked"));
document.querySelector("#link").addEventListener("click", (event) => {
event.preventDefault();
console.log("link clicked, navigation canceled, still bubbling");
});
</script>link clicked, navigation canceled, still bubbling
card clickedpreventDefault canceled the navigation, but the event still bubbled to the card. Calling stopPropagation instead would keep the card's listener from running, but the link would navigate.
Event Delegation
Event delegation means attaching one listener to a common ancestor instead of one listener per child. Because events bubble, the ancestor hears clicks on every child; event.target tells you which one:
<ul id="list">
<li>Navika <button class="remove">Remove</button></li>
<li>Srihitha <button class="remove">Remove</button></li>
</ul>
<button id="add">Add Advitha</button>
<script>
const list = document.querySelector("#list");
list.addEventListener("click", (event) => {
const button = event.target.closest(".remove");
if (!button || !list.contains(button)) return;
button.closest("li").remove();
console.log("Left:", list.children.length);
});
document.querySelector("#add").addEventListener("click", () => {
const li = document.createElement("li");
li.append("Advitha ");
const btn = document.createElement("button");
btn.className = "remove";
btn.textContent = "Remove";
li.append(btn);
list.append(li);
console.log("Added, now:", list.children.length);
});
</script>Left: 1
Added, now: 2
Left: 1Explanation: the single listener on the <ul> handled the Remove button of an item that was added after the listener was registered. event.target.closest(".remove") finds the button even if the click landed on something inside it, and returns null for clicks elsewhere in the list.
| One listener per element | Delegation |
|---|---|
| Must add a listener to every new element | New elements work automatically |
| Hundreds of listeners for hundreds of rows | One listener |
| Must remove listeners when elements are removed | Nothing to clean up |
The Delegation Pattern
container.addEventListener("click", (event) => {
const item = event.target.closest("[data-action]"); // 1. find the element you care about
if (!item || !container.contains(item)) return; // 2. ignore clicks elsewhere
const action = item.dataset.action; // 3. decide what to do
if (action === "remove") removeRow(item.closest("tr"));
if (action === "edit") editRow(item.closest("tr"));
});data-action attributes make the intent of each button explicit, and one listener can handle every action in a component.
Events That Don't Bubble
A few events don't bubble, so a listener on an ancestor never hears them:
| Doesn't bubble | Bubbling alternative for delegation |
|---|---|
focus, blur | focusin, focusout |
mouseenter, mouseleave | mouseover, mouseout (or pointerover, pointerout) |
load, error on images, scroll on elements | Listen in the capture phase, or on each element |
<form id="pay"><input id="amount"><input id="note"></form>
<script>
const form = document.querySelector("#pay");
form.addEventListener("focus", () => console.log("focus on form (never runs)"));
form.addEventListener("focusin", (event) => console.log("focusin:", event.target.id));
</script>focusin: amount
focusin: notefocus didn't bubble to the form; focusin did, so one listener can highlight whichever field is active.
In Practice
The Fee Tracker's payment table uses a single delegated listener for every row action, identified by data-action:
<table><tbody id="rows">
<tr data-id="1"><td>Navika</td><td class="status">due</td>
<td><button data-action="paid">Mark paid</button><button data-action="remove">Remove</button></td></tr>
<tr data-id="2"><td>Srihitha</td><td class="status">due</td>
<td><button data-action="paid">Mark paid</button><button data-action="remove">Remove</button></td></tr>
</tbody></table>
<script>
const rows = document.querySelector("#rows");
rows.addEventListener("click", (event) => {
const button = event.target.closest("[data-action]");
if (!button) return;
const row = button.closest("tr");
if (button.dataset.action === "paid") row.querySelector(".status").textContent = "paid";
if (button.dataset.action === "remove") row.remove();
console.log([...rows.rows].map((r) => `${r.cells[0].textContent}=${r.querySelector(".status").textContent}`).join(" "));
});
</script>Navika=due Srihitha=paid
Srihitha=paidCommon Mistakes
Confusing stopPropagation with preventDefault. One stops travel, the other stops the default action.
Using event.target directly in delegation. If the button contains an icon, target is the icon. Use event.target.closest(selector).
Delegating non-bubbling events. focus and mouseenter never reach the parent. Use focusin or pointerover.
Stopping propagation "just in case". It breaks other code that listens higher up.
Under the Hood
When the browser dispatches an event, it first computes the propagation path: the target and all its ancestors up to window, fixed at the start (so moving or removing elements during dispatch doesn't change who receives it). It then walks the path twice: from window to the target's parent invoking capture listeners, then at the target, then from the target's parent back up invoking bubble listeners. At each node, listeners run synchronously in registration order, each receiving the same event object with currentTarget and eventPhase updated. stopPropagation sets a flag checked between nodes; stopImmediatePropagation is checked between listeners. Default actions run after dispatch finishes, if no listener called preventDefault, which is why cancellation works even from an ancestor's listener. Elements inside a shadow DOM (web components) add one twist: events crossing the shadow boundary are retargeted so outside listeners see the host element as target.
Interview Corner
Explain event bubbling and capturing.
Dispatch has three phases. Capture: the event travels from window down through ancestors to the target, invoking listeners registered with capture: true. Target: listeners on the target run. Bubble: the event travels back up through ancestors invoking normal listeners. Most events bubble; focus, blur, mouseenter and mouseleave don't.
What is event delegation and why use it?
Attaching a single listener to an ancestor and using event.target (usually with closest) to determine which descendant triggered the event. It handles dynamically added elements automatically, reduces the number of listeners and memory use, and needs no cleanup when children are removed.
What does this print when the button is clicked?
Show solution
<div id="d"><button id="b">Go</button></div>
<script>
document.querySelector("#d").addEventListener("click", () => console.log("div"), { capture: true });
document.querySelector("#b").addEventListener("click", (e) => { e.stopPropagation(); console.log("button"); });
document.querySelector("#d").addEventListener("click", () => console.log("div bubble"));
</script>div
buttonThe capture listener on the div runs first, on the way down. The button stops propagation, so the div's bubble listener never runs.
Practice
Challenge: Add one listener to a #menu list that logs the data-page of whichever <li> was clicked, even when the click lands on a <span> inside the item.
Show solution
<ul id="menu">
<li data-page="fees"><span>Fees</span></li>
<li data-page="reports"><span>Reports</span></li>
</ul>
<script>
document.querySelector("#menu").addEventListener("click", (event) => {
const item = event.target.closest("li[data-page]");
if (item) console.log(item.dataset.page);
});
</script>reportsKey Takeaways
| Need | Code |
|---|---|
| Listen during capture | el.addEventListener("click", fn, { capture: true }) |
| Stop travel | event.stopPropagation() |
| Cancel default | event.preventDefault() |
| Delegate | parent.addEventListener("click", (e) => e.target.closest(sel)) |
| Delegate focus | "focusin" / "focusout" |
Was this tutorial helpful?