Skip to content

48 Event Bubbling

Biswajit Sundara edited this page Aug 23, 2023 · 2 revisions

Event bubbling describes the order in which events are propagated or "bubbled" up from the target element to its ancestors in the DOM hierarchy.

  • When an event occurs on a nested element (e.g. a button within a div within a section)
  • It triggers a sequence of event propagation that starts from the innermost element and bubbles up to the outermost parent.
┌───────────────────────────────────────┐
│ Grandparent                           │
│                                       |
│ ┌─────────────────────────────────┐   │
│ │ Parent                          │   │
│ │                                 │   │
│ │ ┌────────────────────────────┐  │   │
│ │ │Child                       │  │   │
│ │ │                            │  │   │
│ │ └────────────────────────────┘  │   │
│ └─────────────────────────────────┘   │
└───────────────────────────────────────┘

Example1

  • So if we click on child div, parent div or grandparent div it will print grand parent is clicked
  • The reason is when we click on the child div/parent div it goes up in the hierarchy up to the root
document.querySelector("#grandparent").addEventListener("click", () => {
  console.log("grand parent clicked");
});
<div id="grandparent">
   <div id="parent">
      <div id="child"></div>
   </div>
</div>

Example2

  • Click on the inner most div, the child div
  • The order of execution will be child div -> Parent div -> grandparent div
document.querySelector("#grandparent").addEventListener("click", () => {
  console.log("grand parent clicked");
});

document.querySelector("#parent").addEventListener("click", () => {
  console.log("Parent clicked");
});

document.querySelector("#child").addEventListener("click", () => {
  console.log("Child is clicked");
});
<div id="grandparent">
   <div id="parent">
      <div id="child"></div>
   </div>
</div

The capture mode

The event listeners have third argument that is the capture mode

  • If it's true then it will be in event capturing mode and propagates from top to bottom
  • If it's false then it's event bubbling mode and propagates from bottom to top
  • By default it's false so in above example we can write
document.querySelector("#child").addEventListener("click", () => {
  console.log("Child is clicked");
}, false);

Clone this wiki locally