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

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.

This question is related to jquery events event-bubbling

The answer is


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();
    }
});

_x000D_
_x000D_
$(document).ready(function(){_x000D_
_x000D_
$("button").click(function(){_x000D_
   _x000D_
       _x000D_
        $(".div3").toggle(1000);_x000D_
    });_x000D_
   $("body").click(function(event) {_x000D_
   if($(event.target).attr('class') != '1' && $(event.target).attr('class') != 'div3'){_x000D_
       $(".div3").hide(1000);}_x000D_
    }); _x000D_
   _x000D_
    _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>_x000D_
<button class="1">Click to fade in boxes</button><br><br>_x000D_
_x000D_
<body style="width:100%;height:200px;background-color:pink;">_x000D_
<div class="div3" style="width:80px;height:80px;display:none;background-color:blue;"></div><body>
_x000D_
_x000D_
_x000D_


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>

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>

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>

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/


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>

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

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.


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.


$('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/


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

Try this:

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

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

  });
});

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();
            });

  $(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...


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();
    }
});

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.


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();
    });