This post will discuss how to hide a div container if a user clicks anywhere on the page outside it in JavaScript and jQuery.

1. Using jQuery

With jQuery, you can bind to the document’s click event and hides the div container when the clicked element isn’t the container itself or a descendant of the div element. This can be implemented as following with jQuery:

jQuery


HTML



Edit in JSFiddle

 
Another plausible way is to use the .closest() method:

jQuery


HTML



Edit in JSFiddle

2. Using JavaScript

Here, the idea is to detect click events on the page and set the container’s display to none only when the target of the click isn’t one of the div descendants.

JS


HTML



Edit in JSFiddle

That’s all about hiding a div on clicking outside it in JavaScript and jQuery.