Close or Hide DIV when clicking outside

Last updated on by , no comments


In this tutorial, I’m gonna demonstrate you how to track if a click event is being made outside of an HTML element.

Through this example, we are going to close or hide div using Jquery when a click action occurs outside of that element on which the DIV was produced by clicking.

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 click event occurs  outside of that dom elements.

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 we do nothing, if it doesn’t, we fadeOut the menu box.

How to hide div when clicking outside


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

	var container = $("#YOUR_TARGETED_ELEMENT_ID");

	if (!container.is(e.target) && container.has(e.target).length === 0){

		container.fadeOut();
		
	}
}); 

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

We are using Jquery’s fadeIn() & fadeOut() functions here to hide and show the box. If you want to use Javascript you can set the css property display block to show the box and display none to hide the box.

To learn more interesting Jquery 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 *