Event bubbling in JavaScript

bishnucit

Bishnu Prasad Chowdhury

Posted on February 25, 2021

Event bubbling in JavaScript

Event bubbling is an event propagation type which is observed in DOM API.

<div>
  <p>
    <img> </img>
  </p>
</div>
Enter fullscreen mode Exit fullscreen mode

For example suppose all 3 elements have registered to handle an event, then as per bubbling rule the event will be handled from inner to outer that is img element will handle the event first then p and last will be div element.

For general use event bubbling is convenient but some rare cases we need to handle outer event first than inner so in those situation we need to avoid event bubbling.

This is achieved by making useCapture true to the event handler function where by default it's passed as false.

btn.addEventListener('click',action item(),true);
Enter fullscreen mode Exit fullscreen mode

OR

To stop bubbling we can use either

// stops immediately
event.stopImmediatePropagation()
Enter fullscreen mode Exit fullscreen mode

Or

//stops after running current event
event.stopPropagation()
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
bishnucit
Bishnu Prasad Chowdhury

Posted on February 25, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related