Categories
JavaScript Answers

How to detect click outside div using JavaScript?

Spread the love

Sometimes, we want to detect click outside div using JavaScript.

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

How to detect click outside div using JavaScript?

To detect click outside div using JavaScript, we can check if e.target doesn’t equal the inner element.

For instance, we write

document.getElementById("outer-container").onclick = (e) => {
  if (e.target !== document.getElementById("content-area")) {
    console.log("You clicked outside");
  } else {
    console.log("You clicked inside");
  }
};

to check that e.target doesn’t equal to document.getElementById("content-area").

If it’s not, then we clicked outside of the element with ID content-area.

We add a click listener to the element with ID outer-container by setting onclick to the click listener function.

Conclusion

To detect click outside div using JavaScript, we can check if e.target doesn’t equal the inner element.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.