# Event Capturing in JavaScript

Event capturing occurs when a nested element gets clicked. The click event of its parent elements must be triggered before the click of the nested element.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1733205961506/5ee08249-449e-45da-a08f-843b8192f2de.png align="center")

Event capturing is not the default behavior of Javascript Events. In vanilla javaScript we need to pass `true` in the 3rd argument of `addEventListener` function to register the handler in event capturing mode.

In React.js we can register the capturing handler via `onClickCapture` function in component.

Now let's see this behavior live in React Application. Here I've created three `div` element with `onClickCapture` 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"
        onClickCapture={(e) => {
          console.log("green!");
        }}
      >
        <div
          className="yellow"
          onClickCapture={(e) => {
            console.log("yellow!");
          }}
        >
          <div
            className="pink"
            onClickCapture={(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 we can inspect the console by clicking on these three different `div.`

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1733205106348/f959932b-1f70-4888-a92b-32488d3eda9e.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 from the root ancestor and `onClickCapture` 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/v1733205584751/590081ad-b98a-4c0c-9b3e-cf4afc4ec69c.png 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)
