Hide element when clicked outside using JavaScript

avatar

Borislav Hadzhiev

Tue Dec 28 20212 min read

banner

Photo by Tobi Oluremi

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'; } });

We added a click handler on the document object.

The first thing we do in the function is to get the DOM element we want to hide when clicked outside. We used the document.getElementById() method in the example.

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

In the example, 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 which 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'; } });

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 in element is not contained in the box element, then the user clicked outside and we hide the box.

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

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee