Last updated: Mar 4, 2024
Reading time·2 min
To hide an element when clicked outside:
click
event listener to the document
object.contains()
method.Here is the HTML for the example.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>bobbyhadz.com</title> </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.
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.
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.
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.
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.
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.
You can learn more about the related topics by checking out the following tutorials: