Twitter Bootstrap mobile nav: hide menu after clicking menu link

后端 未结 7 800
悲&欢浪女
悲&欢浪女 2020-12-15 05:56

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

相关标签:
7条回答
  • 2020-12-15 06:21

    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">
    

    Close on menu item click

    Add to your Javascript accordingly:

    $('#example-auto-collapse').on('click', 'a:not(.dropdown-toggle)', function(e) {
        $('#example-auto-collapse.in').collapse('hide');
    }
    

    Alternative: Close with any click

    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.

    0 讨论(0)
提交回复
热议问题