Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *