Event Bubbling
When an event happens on a web page, it does not stop at just one element. Instead, the event travels through the DOM.
This movement of events is called event bubbling. Understanding it helps you write cleaner and more efficient code.
What Is Event Bubbling?
Event bubbling means that when an event occurs on an element, it first runs on that element and then moves upward to its parent elements.
The event continues bubbling up until it reaches the top of the document.
Simple Example
Imagine this HTML structure:
- A button inside a div
- The div inside the page body
If you click the button, the click event happens on:
- The button
- Then the parent div
- Then the body
Seeing Event Bubbling in Action
let parent = document.getElementById("parent");
let child = document.getElementById("child");
parent.addEventListener("click", function () {
console.log("Parent clicked");
});
child.addEventListener("click", function () {
console.log("Child clicked");
});
Clicking the child element logs both messages because the event bubbles up.
Why Event Bubbling Matters
Event bubbling allows JavaScript to handle events efficiently.
Instead of adding listeners to many elements, you can use a single listener on a parent element.
Real-World Example
Imagine a list of items where each item is clickable.
Instead of adding a click event to every item, you can add one listener to the list container and handle clicks using bubbling.
Stopping Event Bubbling
Sometimes, you may want to stop an event from bubbling further.
child.addEventListener("click", function (event) {
event.stopPropagation();
console.log("Child clicked only");
});
This prevents the event from reaching parent elements.
Common Beginner Mistakes
- Not realizing why multiple handlers run
- Stopping propagation unnecessarily
- Confusing bubbling with capturing
Event bubbling is expected behavior, not a bug.
Thumb Rules
- Events bubble up the DOM by default
- Use bubbling to reduce code repetition
- Stop propagation only when needed
- Always understand the DOM structure
What Comes Next?
Now that you understand how events move through the DOM, the next step is working with user input.
In the next lesson, we will learn about forms and validation.