How to do a hide div when clicking out of it with jQuery?

Asked

Viewed 5,433 times

2

Hello.

How do I get this div to be hidden when I click out of it:

inserir a descrição da imagem aqui

I need her gone when I click out of her.

Follow a similar example:

$("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 inside of it too, I needed it to disappear only when I click outside of it.

Does anyone know how to do this with jQuery?

  • 1

    Opa speaks there, so man, tries to put the title of your question more descriptive, also tries to put the HTML code to make it easier for people to play.

2 answers

2


You have to have an event headset on document and when there is a click verify whether the event.target was inside the widget you have. You can use the .contains() checking whether one item contains another.

For example like:

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>
<div class="div-nome">Clica aqui, ou fora</div>

  • How to make the div hide only when I click out of it?

  • @Newtech changes the place of slideDown and slideUp in my code...

  • 1

    It worked. Thank you!!

  • @Newtech great!

1

Just clicking off 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>
  <div class="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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.