Close or Hide DIV when clicking outside

Last updated on October 17th, 2017 by Paritosh Pandey, no comments

In this tutorial, I’m gonna demonstrate you how to track if a click is being made outside of an HTML element. In this example, we are going to close or hide div when clicking outside of it.

close hide div when clicking outside

If you have ever found with menus boxes that open on click event, but want them to close when a user clicks outside of the menu element, here is a simple way to do so. I’m gonna add an event listener to the document’s body.  When someone clicks it, we look for the event’s targeted id. If the ID is same as the box’s div, then do nothing.  If it doesn’t, fadeOut the menu box.

How to close hide div when clicking outside

$(document).mouseup(function (e){

	var container = $("#YOUR_TARGETED_ELEMENT_ID");

	if (! && container.has( === 0){


Note: don’t forget to change “YOUR_TARGETED_ELEMENT_ID” with your targeted element’s ID.

To learn more interesting web development tricks please subscribe us, and share this article.

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *