Understanding Javascript event propagation: Bubbling and Capturing

Understanding Javascript event propagation: Bubbling and Capturing

Gavin Huynh
Gavin Huynh

Event bubbling and capturing, both are propagation mechanisms in DOM(Document Object Model). Both these mechanisms are opposite of each other.

Understanding DOM Events

DOM event is a signal that something has happened. This can be a user clicking on a button, a page finishing loading, or even an error occurring. JavaScript allows us to listen to these events and define functions, known as event handlers, to be executed when the event occurs.


What is Event Bubbling ?

Event bubbling in Javascript is a mechanism where an event triggered on a child element propagates upward through its ancestors in the DOM. It allows parent elements to respond to events triggered by their child elements.

  • Propagation Direction: In event bubbling, the event starts at the target element and propagates upward through its parent elements to the root of the DOM.
  • Default Behavior: Event bubbling is enabled by default in JavaScript.
  • Event Listeners: If multiple event listeners are attached in the bubbling phase, they are executed in sequence, starting from the innermost target element.
Event bubbling

Example:

If we click on the button, we'll see both 'Child clicked!' and 'Parent clicked!' logged to the console. This is because the click event starts at the button, and then bubbles up to the parent div.


What is Event Capturing ?

Event capturing is a propagation mechanism in the DOM (Document Object Model) where an event, such as a click or a keyboard event, is first triggered at the root of the document and then flows down through the DOM tree to the target element.

Capturing has a higher priority than bubbling, meaning that capturing event handlers are executed before bubbling event handlers, as shown by the phases of event propagation:

  • Propagation Direction: In event capturing, the event starts at root of the document and and then flows down through the DOM tree to target element
  • Default Behavior: Event bubbling is disabled by default in JavaScript.
Event capturing

Example:

Now, if we click on the button, we'll see 'Parent clicked!' logged to the console before 'Child clicked!'. This is because the click event starts at the parent div, and then is captured down to the button.


event.stopPropagation()

stopPropagation() does what the name describes: it stops the propagation of a bubbling event from going further up the tree of elements that it's occurring in.

If you click on the child element, the parent won't be notified of this event.


Conclusion

Understanding event propagation mechanisms is important for handling events in JavaScript. While Bubbling is the default behavior, Capturing could be useful in some situations. It is also important to how to stop the propagation of an event if we don’t want it to affect other elements in the DOM