Hide a div on clicking outside it with JavaScript/jQuery
Hey guys, today in this post we are going to learn about How to close a div container when clicking outside the target. We will use jQuery for that. jQuery is a fast, small, and feature-rich JavaScript library.
We can use the following code:
1. A mouseup event is to first checked upon the document.
3. The element is checked for 2 things, that the click does not land on the element by passing the is() method and the has() method with the click target.
The is() method check the current element against the specified element. The click target is passed as a parameter and the whole result is negated to essentially check if the click was outside the element.
The has() method is used to return all the elements which match at least one of the elements passed to this method. The length property is then used on the result to check if any elements are returned. If there are no elements returned, it means that the click was outside the element.
3. The element is hidden using the hide() method.
$(document).mouseup(function(e)
{
var container = $("YOUR CONTAINER SELECTOR");
// if the target of the click isn't the container nor a descendant of the container
if (!container.is(e.target) && container.has(e.target).length === 0)
{
container.hide();
}
});3 comments
MH
Mahmud Hossain
July 16, 2026
Well written. Bookmarked this for my team's reference. Looking forward to more content like this.
SB
Sumaiya Begum
July 15, 2026
Does this approach also work for larger datasets? Our team is dealing with something similar at scale.
RK
Rafiq Khan
July 14, 2026
Really insightful article! This is one of the clearest explanations I've come across. The examples make it very easy to understand.
AD
AdminAdminJuly 14, 2026Thank you Rafiq! Glad it was helpful.
