How do I hide an element on a click event anywhere outside of the element?

JqueryEventsEvent Bubbling

Jquery Problem Overview


I would like to know whether this is the correct way of hiding visible elements when clicked anywhere on the page.

$(document).click(function (event) {			
	$('#myDIV:visible').hide();
});

The element (div, span, etc.) shouldn't disappear when a click event occurs within the boundaries of the element.

Jquery Solutions


Solution 1 - Jquery

If I understand, you want to hide a div when you click anywhere but the div, and if you do click while over the div, then it should NOT close. You can do that with this code:

$(document).click(function() {
    alert("me");
});
$(".myDiv").click(function(e) {
    e.stopPropagation(); // This is the preferred method.
    return false;        // This should not be used unless you do not want
                         // any click events registering inside the div
});

This binds the click to the entire page, but if you click on the div in question, it will cancel the click event.

Solution 2 - Jquery

Try this

 $('.myDiv').click(function(e) { //button click class name is myDiv
  e.stopPropagation();
 })

 $(function(){
  $(document).click(function(){  
  $('.myDiv').hide(); //hide the button
  
  });
});

I use class name instead of ID, because in asp.net you have to worry about the extra stuff .net attaches to the id

EDIT- Since you added a another piece, it would work like this:

 $('.myDiv').click(function() { //button click class name is myDiv
  e.stopPropagation();
 })

 $(function(){
  $('.openDiv').click(function() {
  $('.myDiv').show(); 
  
  });
  $(document).click(function(){  
  $('.myDiv').hide(); //hide the button
  
  });
});

Solution 3 - Jquery

As of jQuery 1.7 there's a new way to handle events. I thought I'd answer here just to demonstrate how I might go about doing this the "new" way. If you haven't, I recommend you read the jQuery docs for the "on" method.

var handler = function(event){
  // if the target is a descendent of container do nothing
  if($(event.target).is(".container, .container *")) return;

  // remove event handler from document
  $(document).off("click", handler);

  // dostuff
}

$(document).on("click", handler);

Here we're abusing jQuery's selectors and bubbling of events. Note that I make sure I clean the event handler up afterwards. You can automate this behaviour with $('.container').one (see: docs) but because we need to do conditionals within the handler that isn't applicable here.

Solution 4 - Jquery

This following code example seems to work best for me. While you can use 'return false' that stops all handling of that event for the div or any of it's children. If you want to have controls on the pop-up div (a pop-up login form for example) you need to use event.stopPropogation().

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <a id="link" href="#">show box</a>
    <div id="box" style="background: #eee; display: none">
        <p>a paragraph of text</p>
        <input type="file"  />
    </div>

    <script src="jquery.js" type="text/javascript"></script>

    <script type="text/javascript">
        var box = $('#box');
        var link = $('#link');

        link.click(function() {
            box.show(); return false;
        });

        $(document).click(function() {
            box.hide();
        });

        box.click(function(e) {
            e.stopPropagation();
        });
        
    </script>
</body>
</html>

Solution 5 - Jquery

Thanks, Thomas. I'm new to JS and I've been looking crazy for a solution to my problem. Yours helped.

I've used jquery to make a Login-box that slides down. For best user experience I desided to make the box disappear when user clicks somewhere but the box. I'm a little bit embarrassed over using about four hours fixing this. But hey, I'm new to JS.

Maybe my code can help someone out:

<body>
<button class="login">Logg inn</button>
<script type="text/javascript">

	$("button.login").click(function () {
		if ($("div#box:first").is(":hidden")) {
				$("div#box").slideDown("slow");} 
			else {
				$("div#box").slideUp("slow");
				}
	});
	</script>
<div id="box">Lots of login content</div>

<script type="text/javascript">
    var box = $('#box');
    var login = $('.login');

    login.click(function() {
        box.show(); return false;
    });

    $(document).click(function() {
        box.hide();
    });

    box.click(function(e) {
        e.stopPropagation();
    });

</script>

</body>

Solution 6 - Jquery

I did the below. Thought of sharing so someone else could also benefit.

$("div#newButtonDiv").click(function(){
	$(this).find("ul.sub-menu").css({"display":"block"});

	$(this).click(function(event){
		event.stopPropagation();
		$("html").click(function(){
			$(this).find("ul.sub-menu").css({"display":"none"});
		}
	});
});

Let me know if I can help someone on this.

Solution 7 - Jquery

What you can also do is:

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

  var container = $("div");

   if (!container.is(e.target) && container.has(e.target).length === 0)
  {
 container.fadeOut('slow');

   }

});

If your target is not a div then hide the div by checking its length is equal to zero.

Solution 8 - Jquery

Try this:

 $(document).mouseup(function (e) {
    var div = $("#yourdivid");
    if (!div.is(e.target) && div.has(e.target).length === 0) 
    {
       div.hide();
     }
    });

Solution 9 - Jquery

Another way of hiding the container div when a click happens in a not children element;

$(document).on('click', function(e) {
    if(!$.contains($('.yourContainer').get(0), e.target)) {
        $('.yourContainer').hide();
    }
});

Solution 10 - Jquery

  $(document).on('click', function(e) { // Hides the div by clicking any where in the screen
		if ( $(e.target).closest('#suggest_input').length ) {
			$(".suggest_div").show();
		}else if ( ! $(e.target).closest('.suggest_container').length ) {
			$('.suggest_div').hide();
		}
	});

Here #suggest_input in is the name of textbox and .suggest_container is the ul class name and .suggest_div is the main div element for my auto-suggest.

this code is for hiding the div elements by clicking any where in the screen. Before doing every thing please understand the code and copy it...

Solution 11 - Jquery

Try this, it's working perfect for me.

$(document).mouseup(function (e)
{
    var searchcontainer = $("#search_container");

    if (!searchcontainer.is(e.target) // if the target of the click isn't the container...
        && searchcontainer.has(e.target).length === 0) // ... nor a descendant of the container
    {
        searchcontainer.hide();
    }
});

Solution 12 - Jquery

$('html').click(function() {
//Hide the menus if it is visible
});

$('#menu_container').click(function(event){
    event.stopPropagation();
});

but you need to keep in mind these things as well. http://css-tricks.com/dangers-stopping-event-propagation/

Solution 13 - Jquery

Here is a working CSS/small JS solution based on the answer of Sandeep Pal:

$(document).click(function (e)
{
  if (!$("#noticeMenu").is(e.target) && $("#noticeMenu").has(e.target).length == 0)
  {
   $("#menu-toggle3").prop('checked', false);
  }
});

Try it out by clicking the checkbox and then outside of the menu:

https://jsfiddle.net/qo90txr8/

Solution 14 - Jquery

This doesn't work - it hides the .myDIV when you click inside of it.

$('.openDiv').click(function(e) {
$('.myDiv').show(); 
e.stopPropagation();
})

$(document).click(function(){  
$('.myDiv').hide(); 

});

});

<a class="openDiv">DISPLAY DIV</a>

<div class="myDiv">HIDE DIV</div>

Solution 15 - Jquery

Just 2 small improvements to the above suggestions:

  • unbind the document.click when done

  • stop propagation on the event that triggered this, assuming its a click

     jQuery(thelink).click(function(e){
         jQuery(thepop).show();
     				
         // bind the hide controls
       	var jpop=jQuery(thepop);
         jQuery(document).bind("click.hidethepop", function() {
         		jpop.hide();
         		// unbind the hide controls
         		jQuery(document).unbind("click.hidethepop");
         });
         // dont close thepop when you click on thepop
         jQuery(thepop).click(function(e) {
         	e.stopPropagation();
         });
         // and dont close thepop now 
         e.stopPropagation();
     });
    

Solution 16 - Jquery

$(document).ready(function(){

$("button").click(function(){
   
       
        $(".div3").toggle(1000);
    });
   $("body").click(function(event) {
   if($(event.target).attr('class') != '1' && $(event.target).attr('class') != 'div3'){
       $(".div3").hide(1000);}
    }); 
   
    
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<button class="1">Click to fade in boxes</button><br><br>

<body style="width:100%;height:200px;background-color:pink;">
<div class="div3" style="width:80px;height:80px;display:none;background-color:blue;"></div><body>

Solution 17 - Jquery

$( "element" ).focusout(function() {
    //your code on element
})

Solution 18 - Jquery

This is made from the other solutions above.

$(document).ready(function(){  

 	$("button").click(function(event){
    	$(".area").toggle();
    	event.stopPropagation();	//stops the click event to go "throu" the button an hit the document
    });
    
	
	$(document).click(function() {
		$(".area").hide();
	});
	
	
	$(".interface").click(function(event) {
    	event.stopPropagation();
    	return false;        								 
	});
});

<div>
    <div>
    	<button> Press here for content</button> 
      <div class="area">
       	<div class="interface"> Content</div>
      </div>
    </div>       
</div>

Solution 19 - Jquery

$(document).click(function() {
  var container = $("#container");
  if (!container.is(event.target) &&
    !container.has(event.target).length) {
    container.hide();
  }
});


Solution 20 - Jquery

$(document).mouseup(function (e)
{
    var mydiv = $('div#mydiv');
    if (!mydiv.is(e.target) && mydiv.has(e.target).length === 0){
       search.slideUp();
    }
});

Solution 21 - Jquery

Simple Solution: hide an element on a click event anywhere outside of some specific element.

$(document).on('click', function () {
                $('.element').hide();
            });
            //element will not Hide on click some specific control inside document
            $('.control-1').on('click', function (e) {
                e.stopPropagation();
            });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFranekView Question on Stackoverflow
Solution 1 - JqueryJeremy B.View Answer on Stackoverflow
Solution 2 - JqueryTStamperView Answer on Stackoverflow
Solution 3 - JqueryBen TaylorView Answer on Stackoverflow
Solution 4 - JqueryThomasView Answer on Stackoverflow
Solution 5 - JqueryTommyView Answer on Stackoverflow
Solution 6 - JqueryfoxybaggaView Answer on Stackoverflow
Solution 7 - JquerySandeep PalView Answer on Stackoverflow
Solution 8 - JqueryNalan MadheswaranView Answer on Stackoverflow
Solution 9 - JqueryRenato GamaView Answer on Stackoverflow
Solution 10 - JqueryShaikh ArbaazView Answer on Stackoverflow
Solution 11 - JqueryHassan SardarView Answer on Stackoverflow
Solution 12 - JqueryMuhammad TahirView Answer on Stackoverflow
Solution 13 - JqueryBjoergView Answer on Stackoverflow
Solution 14 - JqueryFranekView Answer on Stackoverflow
Solution 15 - JquerycommonpikeView Answer on Stackoverflow
Solution 16 - JqueryEhsan KHANView Answer on Stackoverflow
Solution 17 - JqueryJafar ChoupanView Answer on Stackoverflow
Solution 18 - JqueryNilsView Answer on Stackoverflow
Solution 19 - JqueryKashif ShahzadView Answer on Stackoverflow
Solution 20 - JqueryMohammad GitipasandView Answer on Stackoverflow
Solution 21 - JquerydevView Answer on Stackoverflow