🧠 JavaScript Event Propagation: Capturing vs. Bubbling
🔄 What is Event Propagation?
Event propagation is the process that happens when an event moves through the DOM in three phases:
📌 Capturing Phase (Trickle Down)
element.addEventListener('click', handler, true);
📌 Bubbling Phase (Bubble Up)
element.addEventListener('click', handler); // or false 3rd argument
🧪 Example: Capturing vs. Bubbling in Action
<div id="parent">
<button id="child">Click Me</button>
</div>
// Capturing listener (third argument = true)
document.getElementById("parent").addEventListener("click", () => {
console.log("Parent DIV - Capturing");
}, true);
// Bubbling listener (third argument = false)
document.getElementById("parent").addEventListener("click", () => {
console.log("Parent DIV - Bubbling");
}, false);
// Target element
document.getElementById("child").addEventListener("click", () => {
console.log("Button Clicked");
});
✅ Output When Button Is Clicked
Parent DIV - Capturing
Button Clicked
Parent DIV - Bubbling
🎯 Summary
#JavaScript #Frontend #EventHandling #WebDevelopment #DOM