🧠 JavaScript Event Propagation: Capturing vs. Bubbling

🧠 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:

  1. Capturing Phase (Trickle Down)
  2. Target Phase
  3. Bubbling Phase (Bubble Up)


📌 Capturing Phase (Trickle Down)

  • The event starts at the top (window, document, html, etc.)
  • It moves downward through the DOM to the target element.
  • Less commonly used.
  • You can listen to this phase by passing true as the third argument to addEventListener.

element.addEventListener('click', handler, true);        

📌 Bubbling Phase (Bubble Up)

  • After reaching the target, the event travels upward through the DOM tree to its ancestors.
  • This is the default behavior.
  • Most event listeners work in this phase unless specified otherwise.

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

  • Capturing: true → top-down.
  • Bubbling: false (default) → bottom-up.
  • Use them wisely to control the flow of events in your web app.

#JavaScript #Frontend #EventHandling #WebDevelopment #DOM

To view or add a comment, sign in

Others also viewed

Explore topics