jquery drop down menu closing by clicking outside

I am developing a simple dropdown menu with jquery . When a user press on a trigger area , it will toggle the dropdown area. My question is how to have a click event outside of the dropdown menu so that it close the dropdown menu ?


You can tell any click that bubbles all the way up the DOM to hide the dropdown, and any click that makes it to the parent of the dropdown to stop bubbling.

/* Anything that gets to the document
   will hide the dropdown */
$(document).click(function(){
  $("#dropdown").hide();
});

/* Clicks within the dropdown won't make
   it past the dropdown itself */
$("#dropdown").click(function(e){
  e.stopPropagation();
});

Demo: http://jsbin.com/umubad/2/edit


how to have a click event outside of the dropdown menu so that it close the dropdown menu ? Heres the code

$(document).click(function (e) {
    e.stopPropagation();
    var container = $(".dropDown");

    //check if the clicked area is dropDown or not
    if (container.has(e.target).length === 0) {
        $('.subMenu').hide();
    }
})

You would need to attach your click event to some element. If there are lots of other elements on the page you would not want to attach a click event to all of them.

One potential way would be to create a transparent div below your dropdown menu but above all other elements on the page. You would show it when the drop down was shown. Have the element have a click hander that hides the drop down and the transparent div.

$('#clickCatcher').click(function () { 
  $('#dropContainer').hide();
  $(this).hide();
});
#dropContainer { z-index: 101; ... }
#clickCatcher { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 100; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dropDown"></div>
<div id="clickCatcher"></div>
链接地址: http://www.djcxy.com/p/83964.html

上一篇: 带控件的下拉菜单

下一篇: 通过点击外部jQuery下拉菜单关闭