Categories
JavaScript Answers

How to detect click outside element with JavaScript?

Spread the love

Sometimes, we want to detect click outside element with JavaScript.

In this article, we’ll look at how to detect click outside element with JavaScript.

How to detect click outside element with JavaScript?

To detect click outside element with JavaScript, we can use the element’s contains method.

For instance, we write

const specifiedElement = document.getElementById("a");

document.addEventListener("click", (event) => {
  const isClickInside = specifiedElement.contains(event.target);

  if (!isClickInside) {
    // ...
  }
});

to select the element we want to check with getElemebntById.

Then we add a click listener for the whole page with document.addEventListener.

In the callback, we call specifiedElement.contains with event.target to check if we clicked inside the a element.

If it’s false, then we clicked outside of it.

Conclusion

To detect click outside element with JavaScript, we can use the element’s contains method.

By John Au-Yeung

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

One reply on “How to detect click outside element with JavaScript?”

Leave a Reply

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