Sobes.tech
Junior

What is event bubbling in JavaScript?

sobes.tech AI

Answer from AI

The mechanism by which an event initiated on a DOM element propagates "up" the hierarchy to its parent elements up to the root (document). By default, most events go through three phases:

  1. Capturing phase: The event moves down from the root to the target element. Event listeners attached with the option { capture: true } are triggered during this phase.
  2. Target phase: The event reaches the target element where it was initiated. Listeners attached directly to this element are triggered.
  3. Bubbling phase: The event moves up from the target element to the root of the document. Event listeners attached by default (without { capture: true } or with { capture: false }) are triggered during this phase. This is the phase where "bubbling" occurs in the classical sense.

Bubbling allows for event delegation, where a single listener on a parent element handles events from multiple child elements.

Example:

// HTML:
// <div id="parent">
//   <button id="child">Click me</button>
// </div>

const parent = document.getElementById('parent');
const child = document.getElementById('child');

parent.addEventListener('click', function() {
  console.log('Event bubbled up to the parent');
});

child.addEventListener('click', function() {
  console.log('Event on the target element (button)');
});

// When clicking the 'child' button, the output sequence will be:
// "Event on the target element (button)"
// "Event bubbled up to the parent"

The method event.stopPropagation() can be used to stop further propagation of the event (both capturing and bubbling) after it has been handled by the current listener. The method event.stopImmediatePropagation() stops the bubbling and prevents other listeners on the same element from firing. event.preventDefault() prevents the default browser action associated with the event but does not stop its propagation.

What is event bubbling in JavaScript? — Frontend - sobes.tech