Describe event bubbling in JavaScript and browsers

Answer

Event bubbling in JavaScript is a mechanism where an event propagates from the target element (the element that triggered the event) upward through its ancestors in the DOM hierarchy until it reaches the root (<html> or document).

How Event Bubbling Works

  1. When an event occurs on an element (e.g., a click), the browser first processes the event on that element.
  2. Then, the event propagates up the DOM tree, triggering the same event type on each ancestor element in order.

Example:

<div id="parent">
  <button id="child">Click Me</button>
</div>
<script>
  document.getElementById('parent').addEventListener('click', () => {
    console.log('Parent clicked!');
  });
  document.getElementById('child').addEventListener('click', () => {
    console.log('Child clicked!');
  });
</script>

Output on Button Click:

Child clicked!
Parent clicked!

Use Cases for Event Bubbling

  1. Event Delegation:
document.getElementById('parent').addEventListener('click', (event) => {
  if (event.target.tagName === 'BUTTON') {
    console.log('Button clicked!');
  }
});
  1. Handling Multiple Elements:

Stopping Event Bubbling

Use event.stopPropagation() to prevent the event from propagating to ancestor elements.

Skopiuj kod
document.getElementById("child").addEventListener("click", (event) => {
event.stopPropagation();
console.log("Child clicked! Bubbling stopped.");
});

Event Bubbling vs. Capturing

element.addEventListener('click', handler, true); // Capturing phase
element.addEventListener('click', handler, false); // Bubbling phase (default)

MDN Web Docs: Event Bubbling and Capturing