I\'m looking for a way to make the Twitter Bootstrap mobile/tablet nav automatically hide/collapse after clicking a menu link. I have a lot of menu items and so when users e
Example markup like from the Bootstrap documentation:
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="example-auto-collapse">
Add to your Javascript accordingly:
$('#example-auto-collapse').on('click', 'a:not(.dropdown-toggle)', function(e) {
$('#example-auto-collapse.in').collapse('hide');
}
Like Charlie Dalsass suggested it might be preferable to also close the menu when clicking on the page. For that you can replace the Javascript above with the following:
$('body').click(function(e) {
// don't close when opening a sub-menu in our menu
if(!$(e.target).filter('#example-auto-collapse .dropdown-toggle').length > 0) {
$('#example-auto-collapse.in').collapse('hide');
}
}
Even cleaner imo would be to bind and unbind this handler when the menu opens/closes and avoid running the handler in vain on every single click the user makes. It's very unlikely to have any noticeable impact though.
I created a stack exchange account just to upvote the answer by Skelly for it's simplicity. Then I found out how one can't upvote without reputation. Then I found out how that solution breaks ScrollSpy. Now this is the solution that works best for me without unwanted side effects.