Hide div with fadeToggle when clicking outside it

1

It has a li with the 'user-login-menu' id that when clicked opens a div with a sub-menu, but you can only close it by clicking again on li. I would like it to be possible to close the div by clicking both on and off the li.

I have tried with e.stoppropagation () but it did not work, maybe I applied it wrongly, I would be grateful if anyone 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>
    
asked by anonymous 22.03.2017 / 18:26

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();
});
    
22.03.2017 / 19:14
0

Use the .not() function of jQuery.

It is for you to exclude elements from a selection. So if you do like this:

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

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

});

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

    
22.03.2017 / 20:53