Event bubbling is a mechanism in the DOM where an event starts from the target element and then propagates up through its parent elements all the way to the document root.
For example, if you click a button inside a div, the click event first triggers on the button, then bubbles up to the div, then the body, and so on.
🔹 Example of Event Bubbling
<div id="parent" style="padding: 20px; background: #eee;">
Parent
<button id="child">Click Me</button>
</div>
<script>
document.getElementById("parent").addEventListener("click", () => {
console.log("Parent clicked");
});
document.getElementById("child").addEventListener("click", () => {
console.log("Button clicked");
});
</script>
Clicking the button logs:
Button clicked
Parent clicked
👉 The event bubbles from the button up to the parent div.
🔹 How to Stop Event Bubbling
You can stop bubbling using:
element.addEventListener("click", (event) => {
event.stopPropagation(); // Stops the event from bubbling up
});
Updated example:
document.getElementById("child").addEventListener("click", (e) => {
console.log("Button clicked");
e.stopPropagation(); // Parent won't get the event
});
Now clicking the button only logs:
Button clicked
✅ Key Points
- Event bubbling is default for most events like click, keypress.
- Use
stopPropagation()to prevent the event from reaching parent elements. stopImmediatePropagation()can also prevent other handlers on the same element from running.