Facebook Pixel

What Is Event Bubbling in JavaScript?

Event bubbling is how events propagate up the DOM. Here is how it works (Oyo question).

What Is Event Bubbling in JavaScript?

Event bubbling is when an event on a child element propagates up to its parents. A click on a button inside a div triggers the button's listener, then the div's listener, then the body's, up to the document.

Example

<div id="outer"> <button id="inner">Click</button> </div>
document.querySelector("#outer").addEventListener("click", () => console.log("outer")); document.querySelector("#inner").addEventListener("click", () => console.log("inner")); // clicking the button logs: inner, outer

Three Phases

  1. Capturing (top-down): document -> target's parent.
  2. Target: the event reaches the target element.
  3. Bubbling (bottom-up): target -> document.

By default, listeners run in the bubbling phase. Use the third argument to listen in the capturing phase:

element.addEventListener("click", handler, true); // capturing

Stopping Bubbling

element.addEventListener("click", (e) => { e.stopPropagation(); // stops bubbling to parents });

The Takeaway

Event bubbling: events propagate from the target up to the document. Three phases: capturing (down), target, bubbling (up). Default listeners run in bubbling. Use stopPropagation() to prevent bubbling. Asked by Oyo.

When an event on a child element propagates up to its parents. A click on a button inside a div triggers the button's listener, then the div's listener, up to the document.

Call e.stopPropagation() in the event handler. This prevents the event from propagating to parent elements.

Capturing (top-down: document to target's parent), Target (event reaches the target), and Bubbling (bottom-up: target to document). Default listeners run in the bubbling phase.

Pass true as the third argument to addEventListener: element.addEventListener('click', handler, true). By default (false), listeners run in the bubbling phase.

stopPropagation prevents bubbling to parents but other listeners on the same element still run. stopImmediatePropagation stops both bubbling and other listeners on the same element.

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.