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.
Note: All events bubble up with a few exceptions, like
focus
. To prevent an event from bubbling up, you can useevent.stopPropagation()
.
Consider the four nested elements: body
, article
, div
, and p
.
Clicking on the p element calls the onclick
event handlers in the order:
p
→ div
→ article
.
Notice, we used event.stopPropagation()
inside the article
to prevent an event from bubbling up to the body
element.
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