Reading history

JavaScript Event Bubbling, Capturing and Delegation

7 min read 0 views

Understand how events travel through the page, target vs currentTarget, stopPropagation, and handle many elements with one listener using event delegation.

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.target and event.currentTarget
  • Stopping an event with stopPropagation()
  • Event delegation with closest() and data- 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:

  1. 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.
  2. Target phase: the event reaches the button itself.
  3. 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.target is the element that was actually clicked, the button, and stays the same at every level. event.currentTarget is 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, mouseenter and load, do not; use focusin and focusout when 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 returns null and the handler stops.
  • data-action attributes say what each button does, read through button.dataset.action. The item’s data-id tells 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 when closest could reach a matching ancestor outside it.

Direct Listeners or Delegation?

SituationBetter choice
One or two fixed elements, such as a menu buttonDirect listener on each
Many similar items: table rows, list items, cardsDelegation on the container
Items added or removed while the page runsDelegation
Events that do not bubbleDirect listeners, or a bubbling alternative such as focusin

Common Mistakes

  1. Checking e.target directly, for example e.target.tagName === "BUTTON", which fails when the click lands on an icon inside the button. Use closest().
  2. Calling stopPropagation() by habit. It breaks delegation and analytics higher up; use it only when you have a clear reason.
  3. Confusing stopPropagation() with preventDefault(). The first stops the journey; the second cancels the browser’s default action, such as following a link.
  4. 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).
  • target is where the event started; currentTarget is where the listener is.
  • Delegation puts one listener on a container and uses closest() to find the item.
  • Use stopPropagation() sparingly and preventDefault() for default actions.

Next: URL and URLSearchParams.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *