Event Capturing & Event Bubbling in JavaScript
JavaScript events propagate through the DOM in two main phases: capturing and bubbling.
π Event Flow (Important)
When an event occurs on an element, it goes through three phases:
- Capturing phase (top → down)
- Target phase (event reaches the actual element)
- Bubbling phase (bottom → up)
Window
↓
Document
↓
<html>
↓
<body>
↓
Parent
↓
Child ← event happens here
πΉ Event Capturing (Trickling Phase)
- Event travels from the outermost element to the target element
- Also called event trickling
- Less commonly used than bubbling
- Enabled by passing
trueas the third parameter inaddEventListener
β Example: Event Capturing
<div id="parent">
<button id="child">Click Me</button>
</div>
document.getElementById("parent").addEventListener(
"click",
() => console.log("Parent Capturing"),
true
);
document.getElementById("child").addEventListener(
"click",
() => console.log("Child Capturing"),
true
);
π± When you click the button, output will be:
Parent Capturing
Child Capturing
π§ Why?
- Event starts from parent
- Moves downward to child
- Because capturing is enabled (
true)
πΉ Event Bubbling (Default Behavior)
- Event travels from the target element up to the ancestors
- This is the default behavior in JavaScript
β Example: Event Bubbling
document.getElementById("parent").addEventListener("click", () => {
console.log("Parent Bubbling");
});
document.getElementById("child").addEventListener("click", () => {
console.log("Child Bubbling");
});
π± Output:
Child Bubbling
Parent Bubbling
π§ Why?
- Event fires on child first
- Then bubbles up to parent
π₯ Capturing vs Bubbling (Quick Comparison)
| Feature | Capturing | Bubbling |
|---|---|---|
| Direction | Top → Bottom | Bottom → Top |
| Default | β No | β Yes |
| Usage | Rare | Very common |
| Enabled by | true |
Default / false |
π Stopping Event Propagation
You can stop both capturing and bubbling using:
event.stopPropagation();
π― When Is Event Capturing Used?
- Intercept events before they reach the target
- Security or logging use cases
- Framework-level event handling
- Advanced UI control
π― Short Interview Answer
Event capturing is the phase where an event travels from the outermost parent down to the target element, while event bubbling is when the event moves from the target back up to the ancestors.
Capturing is enabled by setting the third parameter ofaddEventListenertotrue.
β One-line Summary
Capturing goes top-down, bubbling goes bottom-up — bubbling is default, capturing is optional.