Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide a div when clicked outside of it

Tags:

This question has been asked multiple times, however none of the answers seem to work for me.

The css of the div is as follows:

#info{
  display: none;
  position: fixed;
  z-index: 500;
  height: 50%;
  width: 60%;
  overflow: auto;
  background: rgba(187, 187, 187, .8);
}

I tried to use the following code:

$("#info").click(function(e){
  e.stopPropagation();
});

$(document).click(function(){
  $("#info").hide();
});

as well as this code:

$(document).mouseup(function (e){
    var container = $("#info");

    if (container.has(e.target).length === 0) {
        container.hide();
    }
});

Yet whenever i click on the div it also disappears, no clue why but it does.
Any thing else that might work?

like image 807
Gooey Avatar asked Jul 18 '12 15:07

Gooey


People also ask

How do I know if I clicked outside a div?

To detect click outside div using JavaScript, we can check if e. target doesn't equal the inner element. document. getElementById("outer-container").

Can you hide a div?

We hide the divs by adding a CSS class called hidden to the outer div called . text_container . This will trigger CSS to hide the inner div.


2 Answers

As your target has id=info, so you can try:

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

  // check that your clicked
  // element has no id=info

  if( e.target.id != 'info') {
    $("#info").hide();
  }
});

You can also try:

$(document).click(function() {

  if( this.id != 'info') {
    $("#info").hide();
  }

});

According to comment

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

    // check that your clicked
    // element has no id=info
    // and is not child of info
    if (e.target.id != 'info' && !$('#info').find(e.target).length) {
        $("#info").hide();
    }
});
like image 145
thecodeparadox Avatar answered Sep 24 '22 12:09

thecodeparadox


To ensure you have a solution that works on iPads too, then you need to use the following function trigger instead:

$(document).on("mousedown touchstart",function(e){
  var $info = $('#info');
  if (!$info.is(e.target) && $info.has(e.target).length === 0) {
    $info.hide();
  }
});

Similarly, if you are looking to cover off mouseup, add 'touchend':

$(document).on("mouseup touchend",function(e){
  ...
});
like image 38
Andy Lorenz Avatar answered Sep 25 '22 12:09

Andy Lorenz