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