Monday, September 21, 2015

jQuery: How to close a dropdown on clicking anywhere on the body?

jQuery: How to close a dropdown on clicking anywhere on the body? The dropdown is displayed when user click on the 'more' button, to hide the dropdown again user should click on the 'more' button again. But if user want to close the dropdown by clicking anywhere on the body so we need add code on click document.
HTML
-----
<a class="select-link" href="https://www.blogger.com/blogger.g?blogID=3817399277949715318#"><a href="#" class="select-link">Select List</a>
<ul class="dropdown-menu-list">
    <li><a href="#">My item name 1</a></li>
    <li><a href="#">My item name 2</a></li>
    <li><a href="#">My item name 3</a></li>
    <li><a href="#">My item name 4</a></li>
</ul>

CSS
---
.dropdown-menu-list {display:none;}
jQuery
---
$(".select-link").on('click',function(e) {
    e.preventDefault();
    $(".dropdown-menu-list").show();
});

$(document).on('click', function (e) {
 var menu = $(".dropdown-menu-list");
 if(e.target !== menu.get(0) && menu.find($(e.target)).length === 0) {
  menu.animate({top: '100px'}, '200').fadeOut('fast');
  $('.select-link').removeClass('active');

  console.log(e.target);
  console.log(menu.get(0));
  console.log(menu.get(0) !== e.target);
 } 
});