Skip to main content

Event bubbling

Definition

Event bubbling is a mechanism where an event that occurred on a nested element is passed (bubbles) up the DOM tree to its parents.

In other words: if you click a button, the browser first handles the event on the button, then raises it to the container, body, and even document.


Example DOM structure

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

Example: how an event bubbles

javascript
document.querySelector('#child').addEventListener('click', () => { console.log('Button'); }); document.querySelector('#parent').addEventListener('click', () => { console.log('Parent'); }); document.body.addEventListener('click', () => { console.log('BODY'); });

Now clicking the button (#child) prints:

javascript
Button Parent BODY

The handler first fires on the element that was clicked, then the event "bubbles" up the tree to body.


The bubbling mechanism

  1. The event occurs on a specific element → event.target.
  2. Then it is passed upward: target → its parent → document → window.
  3. At every level, the handlers there run, if any.

Visually

javascript
<button> → <div> → <body> → <html> → document

Every level can "hear" the event if it has a handler.


Stopping the bubbling

Sometimes you don't want the event to keep rising. Then you use:

javascript
event.stopPropagation();
javascript
child.addEventListener('click', (e) => { console.log('Button'); e.stopPropagation(); // stopped the bubbling });

Now only this fires:

javascript
Button

Why bubbling is needed

1. Event delegation (saving on handlers)

You can attach a single handler to a parent element and catch events from its children.

javascript
<ul id="menu"> <li>Home</li> <li>Catalog</li> <li>Contacts</li> </ul>
javascript
menu.addEventListener('click', (e) => { if (e.target.tagName === 'LI') { console.log('Clicked item:', e.target.textContent); } });

This works even for new <li> elements added dynamically. It's impossible without bubbling.


2. Global listeners

You can listen for events on the whole document:

javascript
document.addEventListener('click', (e) => { console.log('Click on the page'); });

What does not bubble

Some events do not bubble, for example:

  • blur / focus
  • mouseenter / mouseleave

(they have bubbling equivalents - focusin and focusout).


Summary

ConceptDescription
Event bubblingThe process where an event rises from a nested element to its parents
event.targetThe element where the event occurred
event.currentTargetThe element whose handler is currently running
event.stopPropagation()Stops the bubbling
Used forDelegation, global handlers, logging

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.