JAVASCRIPT Tutorial

Event Bubbling and Capturing

Event Bubbling:

  • Occurs when an event originates from an element within a nested structure (like a DOM tree) and propagates upwards to the outermost (root) element.
  • The event is handled at each element as it "bubbles" up the element hierarchy.

Event Capturing:

  • In contrast to bubbling, capturing starts from the outermost element and propagates downwards to the element where the event originates.
  • The event is handled first at the outermost element, then at each nested element as it "captures" the event.

stopPropagation:

  • A method used to stop the further propagation of an event in the DOM tree.
  • Calling stopPropagation() on an event object prevents it from being handled by any elements above the current element in the event propagation path.

Event Propagation:

  • The process by which events are dispatched and handled through the DOM tree.
  • Propagation can be either bubbling or capturing, depending on the event listener's setting.

JavaScript Example:

// Event Bubbling
document.querySelector('.container').addEventListener('click', (e) => {
  console.log('Container clicked!');
});

document.querySelector('.button').addEventListener('click', (e) => {
  console.log('Button clicked!');
});

// Event Capturing
document.querySelector('.container').addEventListener('click', (e) => {
  console.log('Container clicked!');
}, true);

document.querySelector('.button').addEventListener('click', (e) => {
  console.log('Button clicked!');
});

// Stop Propagation
document.querySelector('.button').addEventListener('click', (e) => {
  e.stopPropagation();
  console.log('Button clicked!');
});

This example demonstrates:

  • Event bubbling: The 'button' click event propagates up to the 'container' element.
  • Event capturing: The 'container' click event listener is executed first and propagates downward to the 'button' element.
  • stopPropagation(): The 'button' click event propagation is stopped, preventing it from reaching the 'container' element.