What is event bubbling?
Event bubbling is a mechanism in JavaScript where an event starts at the target element and then "bubbles up" through its parent elements in the DOM tree.
This means a single click can trigger multiple event handlers — from the inner element to outer containers.
An event first happens on the clicked element, then moves upward like bubbles rising in water.
Example of event bubbling
// HTML structure <div id="parent"> <button id="child">Click me</button> </div> // JavaScript document.getElementById("child").addEventListener("click", function() { console.log("Button clicked"); }); document.getElementById("parent").addEventListener("click", function() { console.log("Parent clicked"); });
When you click the button, both messages appear because the event bubbles up from the button to the parent.
How event bubbling works
- 1. Event happens on the target element
- 2. It moves to the parent element
- 3. Then to the grandparent, and so on
- 4. It continues until it reaches the document
Stopping event bubbling
You can stop the event from bubbling using event.stopPropagation().
document.getElementById("child").addEventListener("click", function(event) { event.stopPropagation(); console.log("Button clicked only"); });
Why event bubbling is useful
- ✔️ Event delegation (efficient event handling)
- ✔️ Fewer event listeners needed
- ✔️ Better performance in large apps
Developers often attach one event listener to a parent instead of many child elements using event bubbling.
Event bubbling vs capturing
- Bubbling → child → parent (default)
- Capturing → parent → child (less common)
Summary
Event bubbling is a process where events move from the target element up through its parents in the DOM tree.
It is a core concept in JavaScript event handling and is widely used in real-world web development.