Hide element when clicked outside using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

Hide element when clicked outside using JavaScript #

To hide an element when clicked outside:

  1. Add a click event listener to the document object.
  2. On each click, check if the clicked element is outside of the specific element using the contains() method.
  3. If the clicked element is outside, hide the original element.

Here is the HTML for the example in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box" style="height: 150px; width: 150px; background-color: salmon"> Box </div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
document.addEventListener('click', function handleClickOutsideBox(event) { const box = document.getElementById('box'); if (!box.contains(event.target)) { box.style.display = 'none'; } });

hide element when clicked outside

We added a click handler on the document object.

We used the document.getElementById() method to select the element we want to hide when the user clicks outside.

The event handler function gets passed the event object as a parameter.

We used the target property on the event object. The target property is a reference to the object (element) on which the event was dispatched.

In other words event.target gives us access to the DOM element the user clicked.

You can console.log the target property to see the DOM element that was clicked by the user.

index.js
document.addEventListener('click', function handleClickOutsideBox(event) { // 👇️ the element the user clicked console.log('user clicked: ', event.target); const box = document.getElementById('box'); if (!box.contains(event.target)) { box.style.display = 'none'; } });

hide element when clicked outside event target

The last step is to use the Node.contains method to check if the clicked element is not contained by the original element.

If the clicked element is not contained in the box, we hide the box element.

The contains() method takes a Node as a parameter and returns a boolean value that indicates if the passed in Node is contained in the Node the method was called on.

If the clicked element is not contained in the box element, then the user clicked outside, so we hide the box.

If the user clicks on the box element, the if condition is not met and the element is not hidden.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.