My Programming Tutorials

My Programming Tutorials

Close or Hide DIV when clicking outside

Last updated on by , 8 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

Author Info

Paritosh Pandey

He loves Technology

Advertisement

8 responses to “Close or Hide DIV when clicking outside”

  1. Irina says:

    Thank you for this helpful tutorial! Why do we use “mouseup” instead of “click”?

    • Paritosh Pandey says:

      Click Event Fires when a mousedown and mouseup event occur on the same element.

      suppose someone mousedown at an element and mouseup at another element by dragging the cursor, it’ll create a little bug I guess.

      However you can use Click event as well.

  2. maxim says:

    How to use class instead of id? Thanks

  3. 7up says:

    Thanks For Great. *****

  4. John says:

    Thank you for all your help. I was having so much trouble with this. Thank you thank you again.

  5. Artem says:

    If a click is first needed to open the layer and only then click to close. What code will be?

Leave a Reply

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