How to only trigger parent click event when a child is clicked with JavaScript?

Sometimes, we want to only trigger parent click event when a child is clicked with JavaScript.

In this article, we’ll look at how to only trigger parent click event when a child is clicked with JavaScript.

How to only trigger parent click event when a child is clicked with JavaScript?

To only trigger parent click event when a child is clicked with JavaScript, we call stopPropagation.

For instance, we write

parent.addEventListener(
  "click",
  (e) => {
    e.stopPropagation();
    console.log("event on parent!");
  },
  true
);

to call addEventListener to listen for clicks on the parent element.

In the event handler, we call stopPropagation to stop the event from going down to the child.

We call it with true to make events propagate down the DOM hierarchy instead of up.

Conclusion

To only trigger parent click event when a child is clicked with JavaScript, we call stopPropagation.