Event Bubbling and Capturing in JavaScript
When an event happens on an element inside another element, both elements can react to the event. This process is controlled by event bubbling and event capturing.
🔹 1. Understanding Event Propagation
JavaScript event propagation happens in three phases:
- Capturing Phase (Trickling Down) – The event starts from the root (
document
) and moves down to the target element. - Target Phase – The event reaches the target element where the actual event happens.
- Bubbling Phase (Going Up) – The event bubbles up from the target element to the root (
document
).
🔹 2. Event Bubbling (Default Behavior)
By default, when an event occurs inside an element, it first triggers the target element's event handler and then bubbles up to its parent elements.
✔ Example: Bubbling Effect
🛠 Output if you click the button (child
):
Since the event bubbles upward, the child event fires first, then the parent.
🔹 3. Event Capturing (Trickling Down)
Event capturing (or trickling) means the event is first captured from the root element down to the target.
To use event capturing, pass true
as the third parameter in addEventListener
.
✔ Example: Capturing Mode
🛠 Output if you click the button (child
):
Here, the parent event fires first because we enabled capturing mode.
🔹 4. Stopping Event Bubbling (stopPropagation
)
If you want to stop the event from propagating up the DOM tree, use event.stopPropagation()
.
✔ Example: Stopping Bubbling
🛠 Output if you click child
:
🚨 Parent’s event is NOT triggered because stopPropagation()
prevented bubbling.
🔹 5. Stopping All Propagation (stopImmediatePropagation
)
If an element has multiple event listeners, it event.stopImmediatePropagation()
stops all event listeners on the element.
✔ Example:
🛠 Output if you click child
:
🚨 The third event does not execute because stopImmediatePropagation()
stops further event listeners on the same element.
🔹 6. Delegating Events (Using Bubbling for Efficiency)
Instead of adding an event listener to each child, attach a single listener to the parent and use event delegation.
✔ Example: Handling Multiple Buttons Efficiently
🛠 Clicking on any <li>
will log its text without adding listeners to each item!
📌 Summary
Concept | Description |
---|---|
Bubbling | Events propagate up the DOM from the target to document . |
Capturing | Events propagate down from document to the target. |
stopPropagation() | Stops event from bubbling up. |
stopImmediatePropagation() | Stops all event listeners on the element. |
Event Delegation | Use bubbling to efficiently handle many child elements with one listener. |
🚀 Mastering bubbling and capturing helps in optimizing event handling in JavaScript!