SmartCodingTips

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.