Hide div with fadeToggle when click out of it

Asked

Viewed 319 times

1

There is a read with the id 'user-login-menu' that when clicked opens a div with a sub-menu, but it is only possible to close it by clicking again on the li. I would like it to be possible to close the div by clicking both on the li and outside it.

I’ve tried with e.stoppropagation() but it didn’t work, maybe I applied it wrong, I’d be grateful if someone could help.

$('#user-login-menu').click(function() {
  $('.dropdown-login').fadeToggle(200, function() {
  });
});
#user-login-menu {
  cursor: pointer;
}

.dropdown-login {
  display: none;
  position: absolute;
  top: 70px;
  right: 0;
  background: #fff;
  width: auto;
  height: auto;
  border-width: 0 1px 1px 1px;
  border-style: solid;
  border-color: rgba(0,0,0,0.3);
}

.dropdown-login li  {
  display: block;
  background: #fff;  
  border: 0;
  width: auto;
  height: auto;
  float: none;
}

.dropdown-login li:hover  {
  background: red;  
}

.dropdown-login li a {
  padding: 0 25px 0 25px;
  text-align: left;
  color: #000;
  font-size: 16px;
  line-height: 40px;
  display: block;
  font-family: 'Roboto', sans-serif;
  font-weight: 700;
  letter-spacing: 0;
}

.dropdown-login li a:hover {
  color: #fff;
}
<li id="user-login-menu"><a>Avatar</a></li>
   <div class="dropdown-login">
      <li><a href="/login/">Login</a></li>
      <li><a href="/registrar/">Registrar</a></li>
   </div>

  • You want it to close by clicking anywhere on the screen other than itself <li>?

  • Yes, close by clicking on the li or anywhere outside it

2 answers

1


Add a click event on body of the document that closes your div:

$(window).click(function() {
    $('.dropdown-login').fadeOut(200);
});

And another click event to stop the spread:

$('#user-login-menu').click(function(event){
    event.stopPropagation();
});
  • It worked in part, it closes by clicking outside, but it is also opening. Any suggestions?

  • @Gabrielsouza try now. I traded the event for 'Ide'.

  • I had even tried with Hide, the problem is that it creates a different animation, as if it were a slide, I would like

  • And if you use the .fadeOut(200)?

  • It worked, thanks! Edit the answer I mark as accepted

  • @Gabrielsouza edited :)

Show 1 more comment

0

Use the function .not() jQuery.

It serves for you to delete elements from a selection. So if you do so:

$('body').not('.dropdown-login').click(function(){

        $('.dropdown-login').fadeToggle(200, function() {});

});

Any clicked element will execute what is in the function click, except the div or element you put in the .not()

  • Unfortunately it didn’t work

  • I updated the code. That was just an example, now it’s adapted to what you’re trying. Copy it and try.

  • It didn’t work, the div opens when I click off and when I click on li the div keeps opening and closing

Browser other questions tagged

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