SyntaxStudy
Sign Up
JavaScript Event Bubbling and Capturing
JavaScript Intermediate 8 min read

Event Bubbling and Capturing

Event Bubbling and Capturing

When a DOM event fires, it does not stay on the target element — it propagates through the DOM tree in three phases: capturing (top-down), at-target, and bubbling (bottom-up). Understanding propagation is key to writing efficient event handling code.

Bubbling

After an event reaches its target, it bubbles upward through ancestor elements, triggering any matching listeners on each. This is the default phase for addEventListener. Bubbling enables event delegation — attaching a single listener on a parent to handle events from many children.

Capturing

Pass true or { capture: true } as the third argument to addEventListener to listen in the capture phase. Capture listeners fire before the target's own listeners.

Stopping Propagation

event.stopPropagation() prevents the event from travelling further along the propagation path. event.stopImmediatePropagation() also prevents other listeners on the same element from firing.

Event Delegation

Use bubbling to attach one listener on a container and handle events from many children dynamically — this is both more efficient and works for elements added after the listener is attached.

Example
const list = document.querySelector('ul');
list.addEventListener('click', function(e) {
  if (e.target.tagName === 'LI') {
    console.log('Clicked item:', e.target.textContent);
  }
});
document.addEventListener('click', function(e) {
  console.log('Bubble reached document');
}, false);
document.addEventListener('click', function(e) {
  console.log('Capture phase:', e.target.tagName);
}, true);
const inner = document.querySelector('.inner');
inner.addEventListener('click', function(e) {
  e.stopPropagation();
  console.log('Stopped here');
});
Pro Tip

Event delegation is a performance best practice — instead of attaching click handlers to every list item, attach one listener on the ul parent and check event.target. It also handles dynamically added items automatically.