Event Bubbling + Modal(Everything's random here BTW)

๐Ÿง  Event Bubbling in JavaScript

Event Bubbling is one of the core concepts of the DOM Event Model in JavaScript. It describes how events propagate (travel) through the DOM tree when an event is triggered.

๐Ÿ” What is Event Bubbling?

When an event occurs on a nested element (like a button inside a div), it first runs the event handler on the target element, and then it "bubbles up" the DOM tree to its ancestors โ€” triggering any matching event handlers on parent elements, all the way up to the root.

Example:


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

Clicking the button logs:

๐ŸŒณ Event Propagation Phases

  1. Capturing Phase: The event travels from the root down to the target element (rarely used).
  2. Target Phase: The event reaches the actual element where it occurred.
  3. Bubbling Phase: The event bubbles back up to the root, calling handlers along the way.

โœ‹ How to Stop Event Bubbling

You can stop the bubbling using the event.stopPropagation() method:


  document.getElementById('child').addEventListener('click', (e) => {
    e.stopPropagation();
    console.log('Child clicked (no bubbling)');
  });
      

๐Ÿงช Use Cases of Event Bubbling

โš ๏ธ Things to Remember

๐Ÿ’ก Tip: Try clicking nested elements and logging from multiple levels to understand how bubbling works in action!