Event Capturing in JavaScript

Rohit SawRohit Saw
2 min read

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.

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.

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>
  );
}
.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.

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.

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
0
Subscribe to my newsletter

Read articles from Rohit Saw directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rohit Saw
Rohit Saw

FullStack Developer