# Event Bubbling in JavaScript

Event Bubbling is a concept of event propagation in the DOM. when an event occurs inside an HTML element. it gets propagated or bubbles up to its parent and ancestor element in the DOM tree until it gets to the root element.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1690785713634/fb3fb1e0-ecbe-45ee-b3e5-4d6c206d2407.jpeg align="center")

Now let's see this behavior live in React Application. Here I've created three `div` element with `onClick` event handler so that we can `console.log` if this event handler gets executed on this element.

```javascript
import "./styles.css";

export default function App() {
  return (
    <div className="App">
      <div
        className="green"
        onClick={(e) => {
          console.log("green!");
        }}
      >
        <div
          className="yellow"
          onClick={(e) => {
            console.log("yellow!");
          }}
        >
          <div
            className="pink"
            onClick={(e) => {
              console.log("pink!");
            }}
          ></div>
        </div>
      </div>
    </div>
  );
}
```

```css
.App {
  font-family: sans-serif;
  text-align: center;
}

.green {
  background-color: green;
  width: 600px;
  height: 600px;
  position: absolute;
}

.yellow {
  background-color: yellow;
  width: 400px;
  height: 400px;
  position: absolute;
  top: 100px;
  left: 100px;
}

.pink {
  background-color: pink;
  width: 200px;
  height: 200px;
  position: absolute;
  top: 100px;
  left: 100px;
}
```

Now UI will look like this. So now when we inspect the console by clicking on these three different `div.`

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1690641076633/4a8bd8ac-8aec-47c2-90e4-6dbb22e01083.png align="center")

If we click on the different color box. we get these outputs in consoles. which clearly shows how `click` events get propagated till the root ancestor and `onClick` event handler gets executed for each of these `div.` We can stop this propagation at any `div` by calling `e.stopPropagation()` on any event handler so this event will not get propagated further.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1690787354269/ab79a708-413d-4645-8326-c734350672b8.jpeg align="center")

Hope this helps! Let me know if you have any other questions.

**Resources**

1. [https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation)
