My Programming Tutorials

Close or Hide DIV when clicking outside

Last updated on by , 4 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.has( === 0){


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

Close or Hide DIV when clicking outside
5 (100%) 2 votes

4 Responses
  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

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.