JavaScript event bubbling

Event bubbling is a way of event propagation in the HTML DOM. It relates to the order in which events are propagated in nested elements.



In bubbling, when an event happens, the handler of the innermost element runs, then the parents, and then the further ancestor elements. In other words, events bubble up or propagate the DOM tree upwards.

Events bubble up
Events bubble up

Note: All events bubble up with a few exceptions, ​like focus. To prevent an event from bubbling up, you can use event.stopPropagation().

Example

Consider the four nested elements: body, article, div, and p.

Clicking on the p element calls the onclick event handlers in the order:
pdivarticle.

Notice, we used event.stopPropagation() inside the article to prevent an event from bubbling up to the body element.

  • HTML
Console

A similar principle to event bubbling is event capturing, where events propagate inwards instead of outwards. Event bubbling and event capturing lay the foundation of event delegation.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved