DEV Community

loading...

Event bubbling in JavaScript

bishnucit profile image Bishnu Prasad Chowdhury ・1 min read

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

Discussion (0)

pic
Editor guide