When you click a button, the click does not happen only on the button. The event travels down the page from the top to the button, then back up through every parent element. Understanding this journey, called event propagation, explains many puzzling bugs and unlocks event delegation: handling clicks on any number of elements, even ones created later, with a single listener.
In this lesson you will learn
- The capture and bubble phases of an event
- The difference between
event.targetandevent.currentTarget - Stopping an event with
stopPropagation() - Event delegation with
closest()anddata-attributes - When delegation is the right choice
You should know events and DOM traversal.
Capturing and Bubbling
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Bubbling and capturing</title>
<style>
body { font-family: sans-serif; margin: 12px; font-size: 14px; }
div { padding: 10px; border: 2px solid #90a4ae; border-radius: 6px; }
#outer { background: #eceff1; } #inner { background: #e3f2fd; }
button { padding: 6px 10px; }
#log { font-family: monospace; font-size: 12px; min-height: 60px; }
</style>
</head>
<body>
<div id="outer">outer
<div id="inner">inner
<button id="btn">Click me</button>
<label><input type="checkbox" id="stop"> stop at inner</label>
</div>
</div>
<p id="log"></p>
<script>
var log = document.getElementById("log");
function write(text) { log.textContent += text + " → "; }
// Capturing listeners run first, from the top down
document.getElementById("outer").addEventListener("click", function () {
log.textContent = ""; // runs first, so start a fresh log here
write("outer (capture)");
}, { capture: true });
// Bubbling listeners (the default) run from the target up
document.getElementById("btn").addEventListener("click", function (e) {
write("button: target=" + e.target.id);
});
document.getElementById("inner").addEventListener("click", function (e) {
write("inner: currentTarget=" + e.currentTarget.id);
if (document.getElementById("stop").checked) e.stopPropagation();
});
document.getElementById("outer").addEventListener("click", function (e) {
write("outer: target=" + e.target.id);
});
</script>
</body>
</html>
Result
Click the button. The log shows the order in which the listeners ran:
- Capture phase: the event travels from the top of the document down towards the target. Listeners added with
{ capture: true }run now, so “outer (capture)” comes first. - Target phase: the event reaches the button itself.
- Bubble phase: the event travels back up through each parent. Ordinary listeners run in this phase, so the inner box comes before the outer one.
event.targetis the element that was actually clicked, the button, and stays the same at every level.event.currentTargetis the element whose listener is running now.- Tick “stop at inner” and click again:
stopPropagation()in the inner listener stops the event bubbling further, so the outer bubbling listener never runs. - Click the inner box’s background instead of the button, and the target becomes
inner. - Most events bubble. Some, such as
focus,blur,mouseenterandload, do not; usefocusinandfocusoutwhen you need bubbling focus events.
Event Delegation
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Event delegation</title>
<style>
body { font-family: sans-serif; margin: 12px; font-size: 14px; }
li { display: flex; gap: 8px; align-items: center; margin: 4px 0; }
li.done span { text-decoration: line-through; color: #9e9e9e; }
button { cursor: pointer; }
</style>
</head>
<body>
<form id="add"><input id="text" placeholder="New task" required> <button>Add</button></form>
<ul id="tasks">
<li data-id="1"><span>Read chapter 5</span><button data-action="done">Done</button><button data-action="delete">Delete</button></li>
<li data-id="2"><span>Solve 10 sums</span><button data-action="done">Done</button><button data-action="delete">Delete</button></li>
</ul>
<p id="info"></p>
<script>
var list = document.getElementById("tasks");
var nextId = 3;
// ONE listener on the list handles every button, including ones added later
list.addEventListener("click", function (e) {
var button = e.target.closest("button[data-action]");
if (!button || !list.contains(button)) return; // the click was not on a button
var item = button.closest("li");
if (button.dataset.action === "done") item.classList.toggle("done");
if (button.dataset.action === "delete") item.remove();
document.getElementById("info").textContent =
button.dataset.action + " on task " + item.dataset.id;
});
document.getElementById("add").addEventListener("submit", function (e) {
e.preventDefault();
var input = document.getElementById("text");
var li = document.createElement("li");
li.dataset.id = nextId++;
var span = document.createElement("span");
span.textContent = input.value; // safe: no HTML parsing
li.append(span);
["done", "delete"].forEach(function (action) {
var b = document.createElement("button");
b.dataset.action = action;
b.textContent = action === "done" ? "Done" : "Delete";
li.append(b);
});
list.append(li); // no new listener needed
input.value = "";
});
</script>
</body>
</html>
Result
- Instead of adding a listener to every button, there is one listener on the list. Clicks on any button bubble up to it.
e.target.closest("button[data-action]")finds the button that was clicked, even if the click landed on an icon or text inside it. If the click was elsewhere, it returnsnulland the handler stops.data-actionattributes say what each button does, read throughbutton.dataset.action. The item’sdata-idtells you which record to change.- Add a new task: its buttons work immediately, with no new listener. This is the biggest advantage of delegation.
list.contains(button)makes sure the match is inside the list, which matters whenclosestcould reach a matching ancestor outside it.
Direct Listeners or Delegation?
| Situation | Better choice |
|---|---|
| One or two fixed elements, such as a menu button | Direct listener on each |
| Many similar items: table rows, list items, cards | Delegation on the container |
| Items added or removed while the page runs | Delegation |
| Events that do not bubble | Direct listeners, or a bubbling alternative such as focusin |
Common Mistakes
- Checking
e.targetdirectly, for examplee.target.tagName === "BUTTON", which fails when the click lands on an icon inside the button. Useclosest(). - Calling
stopPropagation()by habit. It breaks delegation and analytics higher up; use it only when you have a clear reason. - Confusing
stopPropagation()withpreventDefault(). The first stops the journey; the second cancels the browser’s default action, such as following a link. - Adding a listener inside a loop to items that will later be re-rendered, leaving them without handlers.
Practice Exercises
Exercise 1. A table with id="results" has many rows. Write one listener that logs the text of the first cell of whichever row is clicked.
Show answer
document.getElementById("results").addEventListener("click", (e) => {
const row = e.target.closest("tr");
if (row) console.log(row.cells[0].textContent);
});
Exercise 2. Clicking anywhere outside an open menu (#menu) should close it. How can delegation on document do this?
Show answer
document.addEventListener("click", (e) => {
if (!e.target.closest("#menu")) document.getElementById("menu").hidden = true;
});
If the button that opens the menu sits outside #menu, also ignore clicks on it, or this listener will close the menu as soon as it opens.
Frequently Asked Questions
Does delegation make pages faster?
It uses fewer listeners and less memory, which helps on long lists, and it avoids re-adding listeners after each update. For a handful of elements, the difference is too small to notice.
What does stopImmediatePropagation do?
Like stopPropagation it stops the event moving to other elements, and it also prevents any other listeners on the same element from running.
Summary
- Events travel down (capture), reach the target, then travel up (bubble).
targetis where the event started;currentTargetis where the listener is.- Delegation puts one listener on a container and uses
closest()to find the item. - Use
stopPropagation()sparingly andpreventDefault()for default actions.
Next: URL and URLSearchParams.
