Bubbling vs Capturing in JavaScript
Events in JavaScript follow a flow called the **event propagation model**, which has two main phases: Capturing (top-down) and Bubbling (bottom-up).
๐ฝ Capturing Phase
The event starts from the <html>
element and travels down to the target element. Capturing is rarely used.
๐ผ Bubbling Phase
The event starts from the target element and bubbles up to the root. Most event listeners in JavaScript use bubbling by default.
๐ Example Structure
<div id="parent">
<button id="child">Click Me</button>
</div>
๐งช Bubbling Example (Default)
document.getElementById("parent").addEventListener("click", () => {
console.log("Parent clicked (bubbling)");
});
document.getElementById("child").addEventListener("click", () => {
console.log("Child clicked");
});
Clicking the button logs both messages โ child first, then parent.
๐ฅ Capturing Example (Third Argument: true
)
document.getElementById("parent").addEventListener("click", () => {
console.log("Parent clicked (capturing)");
}, true);
document.getElementById("child").addEventListener("click", () => {
console.log("Child clicked");
});
Now the parent logs first because it's in the capturing phase.
๐ซ Stopping Propagation
document.getElementById("child").addEventListener("click", (e) => {
e.stopPropagation();
console.log("Only child logs, bubbling stopped");
});
๐ก Tip: Use
stopPropagation()
cautiously โ it may block essential parent logic.