Categories
JavaScript Answers

How to detect click inside/outside of element with single event handler with JavaScript?

Spread the love

Sometimes, we want to detect click inside/outside of element with single event handler with JavaScript.

In this article, we’ll look at how to detect click inside/outside of element with single event handler with JavaScript.

How to detect click inside/outside of element with single event handler with JavaScript?

To detect click inside/outside of element with single event handler with JavaScript, we use the element contains method.

For instance, we write

const myElementToCheckIfClicksAreInsideOf =
  document.querySelector("#my-element");

document.body.addEventListener("click", (event) => {
  if (myElementToCheckIfClicksAreInsideOf.contains(event.target)) {
    console.log("clicked inside");
  } else {
    console.log("clicked outside");
  }
});

to add a click listener for the myElementToCheckIfClicksAreInsideOf container element with addEventListener.

In it we call myElementToCheckIfClicksAreInsideOf.contains to check if the element that we clicked on is in myElementToCheckIfClicksAreInsideOf .

event.target is the element that we clicked on.

Conclusion

To detect click inside/outside of element with single event handler with JavaScript, we use the element contains method.

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 *