简体   繁体   中英

closing a div while click anywhere outside that div

I am trying to create a jquery navigation bar. So when I click on div main, a new div will slide down and I want to add an option to close the window if we click anywhere outside the newly opened window. This is the code that I have used but it is not working.

The newly opened div doesn't close when I click anywhere outside it.

var $s = $("#main");    
$(document).ready(function () 
{
  $(document.body).click(function()
  {
   $('ul.the_menu').slideToggle('medium');
   if (!$s.has(this).length) 
   {
      $s.hide();
   }    
 });
});

Do you mean something like:


if(!$(event.target).is('#main')) {
   // your code to close the div
}

You can do this by attaching an event to the "body" of the page is the simplest approach.

    $("body").click(function () {
        ....
    });

You are trying to use a javascript dom reference, where you need to use a jquery selector to apply jquery events.

I see this question asked at least once a week. I usually get away with this but it depends on your logic and markup.

$menu.focusout(function(){ 
    $(this).slideUp(); 
})
var $_theDiv = $('#the_div')

$_theDiv.click(function(e){
    e.stopPropagation();
} );
// stops the event from bubbling up to the body.

$(document).click(function(){ $_theDiv.hide(); });
//Now any time a click event bubbles to the top of the document, you know it wasn't #theDiv

I'm going to go with a basic example to get to the general idea. We show #theDiv. Now we want it to disappear if we click anywhere but on #theDiv. So we use stopPropagation on the event object. Normally when you click, the click also goes up the parent, and the parent of that parent, and keeps going until you hit the document. This is called "event bubbling." Since we stopped the bubbling, we know if a click reaches the document (the HTML tag), that it couldn't have come from #theDiv because e.stopPropagation, prevented it. Bubbling is very useful, so only use stopPropagation on elements that have no children (aren't containers). Things like links and images and buttons.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM