Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Event Bubbling and Delegation in JavaScript

· 6 min read · Home Tech

In this article
  1. Background: How Events Flow in the DOM
  2. How Event Bubbling Works
  3. Event Delegation: One Listener to Rule Them All
  4. Why Use Event Delegation?
  5. Common Pitfalls and How to Avoid Them
  6. Event Bubbling vs. Capturing
  7. Alternatives to Delegation
  8. Frequently Asked Questions

Event bubbling and event delegation are core JavaScript concepts that explain how events travel through the DOM and how you can handle them efficiently. Bubbling is the default propagation phase where an event triggered on a nested element moves up through its ancestors, and delegation is a technique that leverages bubbling to handle events for multiple elements with a single listener.

Background: How Events Flow in the DOM

When a user clicks a button inside a div, the browser doesn't just fire the event on the button. It fires it on the button first, then on its parent, then on the grandparent, and so on up to the document root. This is the bubbling phase. There's also a capturing phase that goes the opposite direction—from the root down to the target—but it's less commonly used. The DOM Events specification defines three phases: capture, target, and bubble. Most event handlers you write with addEventListener default to the bubble phase.

This behavior might seem like a nuisance at first—why should a click on a button also trigger a handler on the body? But it's actually what makes event delegation possible and is a fundamental part of how interactive web pages work.

How Event Bubbling Works

Consider this HTML:

<div id="parent">
  <button id="child">Click me</button>
</div>

If you attach a click handler to both the div and the button, clicking the button will execute the button's handler first, then the div's handler. The event “bubbles up” from the target (button) to its ancestors (div, body, html, document).

You can stop this propagation using event.stopPropagation() inside a handler. This prevents the event from reaching any other element in the bubble phase. There's also event.stopImmediatePropagation(), which also stops other handlers on the same element from running. However, stopping propagation can sometimes break other functionality, especially if you're using delegation, so use it sparingly.

Event Delegation: One Listener to Rule Them All

Event delegation is a pattern where you attach a single event listener to a common ancestor, and then use logic inside that listener to determine which descendant triggered the event. This is possible because of bubbling—the event from any child will eventually reach that ancestor.

For example, instead of adding a click handler to every li in a list, you add one to the ul:

document.querySelector('ul').addEventListener('click', function(e) {
  if (e.target.tagName === 'LI') {
    console.log('You clicked', e.target.textContent);
  }
});

Here, e.target is the actual element that was clicked. You can check if it's an li (or any other selector using e.target.closest()) and then act accordingly. This works even for elements added to the DOM after the listener is attached—a huge advantage for dynamic interfaces.

Why Use Event Delegation?

The primary benefit is performance. Attaching hundreds of individual listeners can slow down your page, especially on mobile devices. Each listener takes up memory and increases the time it takes to set up. With delegation, you use just one listener, which is faster to initialize and uses less memory.

Another benefit is simplicity. If you have a list of items that can be added or removed, you don't need to attach and remove listeners each time. The single delegated listener handles all current and future elements automatically. This also makes your code cleaner and easier to maintain.

Delegation is particularly useful for:

  • Lists and tables with many rows
  • Menus or accordions with multiple interactive items
  • Dynamic content loaded via AJAX
  • Any situation where you'd otherwise write a loop to attach listeners

Common Pitfalls and How to Avoid Them

One common mistake is not checking the target element. If you attach a delegated listener to a div that contains text and a button, clicking the text will also trigger the handler. Always verify that e.target matches what you expect, using closest() or a tag name check.

Another pitfall is inadvertently breaking other handlers with stopPropagation(). If you have a delegated listener on the document and you stop propagation on a button, the document listener will never fire. This can cause mysterious bugs. Only stop propagation when you're sure it's necessary.

Also, be careful with e.target vs e.currentTarget. e.target is the element that was clicked (the deepest one), while e.currentTarget is the element where the listener is attached (the ancestor). In a delegated handler, you almost always want e.target to identify the actual source.

Event Bubbling vs. Capturing

While bubbling travels up, capturing travels down. In the capturing phase, the event starts at the root and moves down to the target. You can listen to the capturing phase by passing true as the third argument to addEventListener.

In practice, you'll rarely use capturing. It's mainly useful for intercepting events before they reach their target, such as in drag-and-drop logic or when you need to handle events that might be stopped from bubbling. The default bubble phase is sufficient for most delegation scenarios.

Here's a quick comparison:

  • Bubbling: Target → Parent → Grandparent → ... → Document
  • Capturing: Document → Grandparent → Parent → Target

Both phases run for every event, but by default your handlers only run in the bubble phase (unless you specify capture).

Alternatives to Delegation

If you don't want to use delegation, you can attach listeners directly to each element. This is simpler to understand but less efficient for large numbers of elements. Modern frameworks like React and Vue handle this internally with synthetic events, but understanding the underlying DOM behavior still helps when debugging.

Another alternative is using event delegation libraries, but with modern closest() and matches() methods, you rarely need them. The native approach is clean and fast.

Frequently Asked Questions

What is the difference between event.target and event.currentTarget?

event.target is the element that actually triggered the event (the deepest element clicked). event.currentTarget is the element to which the listener is attached. In a delegated listener, they are different—currentTarget is the ancestor, target is the child.

Does event delegation work for all events?

No. Only events that bubble can be delegated. Most UI events like click, keydown, and input bubble. However, some events like focus and blur do not bubble, though you can use the focusin and focusout events which do. Also, events like scroll and resize don't bubble, but you can still catch them on the window.

How do I delegate events for dynamically added elements?

You don't need to do anything special. As long as the listener is attached to a common ancestor that exists at the time of attachment, it will catch events from any descendants added later. This is the main advantage of delegation.

Should I always use event delegation?

No. For a few elements, direct listeners are simpler and more readable. Delegation shines when you have many elements or dynamic content. Use your judgment—if you find yourself writing loops to attach listeners, consider delegation.

Can I stop event bubbling and still use delegation?

If you call stopPropagation() on an event, it won't reach the delegated ancestor, so that handler won't fire. This can be intentional to isolate behavior, but it can also break delegation. If you need to stop the event from going further but still want to handle it, consider using a flag or handling it in the same listener.