简体   繁体   中英

click outside bootstrap menu to close it

I tried to find solution to close bootstrap menu when clicking outside of it(in mobile window size), but cant get it to work, I get it to work when clicking one of the 'a' links by this code:

// menu buttons collapses when clicking a link
    $('document').ready(function() 
{
    if ($('a').on('click', function() 
            { 
                $('.collapse, #mainContainer').removeClass('in'); 
                $('.navbar-toggle').toggleClass('collapsed'); // button
            }));
});

but how to close menu by clicking outside the menu navbar?

here's my page that shows the problem iwebdesign.se

and yes i tried this already, not working:

similar question

  $(document).on('click',function(){
   $('.collapse').collapse('hide');
});

Just copy the code and past your custome script or index.html

thank's Remy click outside to hide bootstrap toggle menu close(hide) it

Here the answer :

   (document).on('click',function(){
   $('.collapse').collapse('hide');
})

Hope it's help :)

Remy

Assuming you want to do something different when clicking outside of the menu (ie collapse the menu) than what happens when you click inside the menu, you probably want something like this to determine if you're clicking inside or outside of the menu:

$('body').click(function(event){
  // check if the clicked element is a descendent of navigation 
  if ($(event.target).closest('.navigation').length) {
    return; //do nothing if event target is within the navigation
  } else {
  // do something if the event target is outside the navigation
     // code for collapsing menu here...
  }
});

https://jsfiddle.net/L3qg4pa8/5/ shows the concept, roughly.

Of course, you will need to replace '.navigation' in the .closest() statement with the appropriate selector for the container of your navigation.

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