HomeJAVASCRIPTExplain event bubbling and capturing.

Explain event bubbling and capturing.

In JavaScript, when an event (like click) happens on an element inside the DOM tree, it doesn’t just affect that element—it also affects its parent elements. This process of how the event moves through the DOM is called the event flow, and it has two main phases:


1. Event Capturing (Trickling Down Phase)

  • The event starts from the top-most ancestor (window → document → html → body → ...) and moves downward toward the target element.
  • At this stage, JavaScript checks each ancestor element along the way, but by default, event handlers don’t run in capturing phase unless explicitly told.
  • You can enable capturing by passing true as the third argument to addEventListener.

👉 Example:

document.getElementById("parent").addEventListener("click", () => {
  console.log("Parent (capturing)");
}, true); // 'true' = capturing phase

2. Event Bubbling (Going Up Phase)

  • After the event reaches the target element and runs its handler, it bubbles up through the ancestors in reverse order:
    target → parent → body → html → document → window.
  • By default, most events in JavaScript use bubbling.

👉 Example:

document.getElementById("child").addEventListener("click", () => {
  console.log("Child (bubbling)");
}); // default is bubbling

3. Target Phase

  • The middle point where the event actually happens on the target element itself before bubbling up.

Quick Example with Both:

HTML:

<div id="parent">
  <button id="child">Click Me</button>
</div>

JS:

document.getElementById("parent").addEventListener("click", () => {
  console.log("Parent (bubbling)");
}); 

document.getElementById("child").addEventListener("click", () => {
  console.log("Child (target)");
}); 

document.getElementById("parent").addEventListener("click", () => {
  console.log("Parent (capturing)");
}, true);

📌 If you click the child button, the log order will be:

Parent (capturing)   // capturing phase
Child (target)       // target phase
Parent (bubbling)    // bubbling phase

Summary:

  • Capturing: top → down
  • Target: event fires on the clicked element
  • Bubbling: bottom → up (default in JavaScript)

👉 Developers mostly use bubbling for features like event delegation because it’s easier to manage events on parent elements.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *