How to make a div hide when clicking off it with jQuery?

2

Hello.

How do I hide this div when I click outside it:

IneedittodisappearwhenIclickoutsideit.

Here'sasimilarexample:

$("body").on("click", function() {
   $(".passageiros-div").slideUp("slow/400/fast");
});
.passageiros-div {
  border: 1px solid #000;
}
<!DOCTYPE html>
<html>
<head>
	<title>Teste</title>
</head>
<body>
  <div class="passageiros-div">
    <p>Titulo</p>
  </div>
  <div>
    <h1>Frase de Teste</h1>
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
</body>
</html>

Notice that when I click on it it also disappears, I need it to disappear only when I click outside it.

Does anyone know how to do this with jQuery?

    
asked by anonymous 08.06.2017 / 20:07

2 answers

1

You must have an event handset in document and when there is a click check if event.target was within the element you have. You can use .contains() that checks if one element contains another.

For example like this:

var divNome = document.querySelector(".div-nome");
$(document).on("click", function(e) {
  var fora = !divNome.contains(e.target);
  if (fora) $(divNome).slideDown("slow/400/fast");
  console.log(fora ? 'Fora!' : 'Dentro!');
});


$(divNome).on("click", function(e) {
  $(this).slideUp("slow/400/fast");
});
.div-nome {
  padding: 30px;
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="div-nome">Clica aqui, ou fora</div>
    
08.06.2017 / 20:21
2

Just clicking outside the div

$(document).mouseup(function(e) 
{
    var container = $(".passageiros-div");

    if (!container.is(e.target) && container.has(e.target).length === 0) 
    {
        container.hide();
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><body><divclass="passageiros-div">
<p>Paragrafo dentro da div a ser ocultada</p>
  </div>
  <div>
<h1>titulo fora da div a ser ocultada</h1>
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
</body>
    
08.06.2017 / 20:22