What is bubbling and how it works

Capturing

Capturing is a process of event propagation that starts from the top of the DOM tree (generally Document) and goes downward till reaching event target. All capturing `EventListeners` of the appropriate type, registered on ancestors of the event’s target will be intercepted and triggered.

addEventListener(type, listener, useCapture)

To use capturing we have to set third parameter of addEventListener to true. By default it’s value is set to false.

Bubbling

It’s a process of upward propagation of the event that takes place after reaching event target. During this process all event listeners found on parent chain will be triggered by bubbling events. This upward propagation will continue till reaching the Document (Document is included).

Event listeners registered as capturers will be omitted.

Stop propagation

Event propagation can be stoped by calling stopPropagation method of the event object. It works for event listeners using capturing and bubbling. Additional event listeners registered at the same hierarchy level will still receive the event.

Preventing default events

Some events have cancelable read-only property (event.canclable).

This means that it is possible to cancel event’s default action. Default action can be canceled with:

event.preventDefault()

Most browser-native events that can be canceled are the results of users interactions with the page (scroll , click).

Resources

  1. w3.org – Document Object Model Events
  2. w3.org – DOM Event Architecture
  3. dom.spec.whatwg.org – events
  4. developer.mozilla.org – Introduction to events