简体   繁体   中英

Automatically close Toggle-nav menu upon menu selection

I need help in automatically closing a toggle-nav menu on mobile. Right now it doesn't close when a menu is selected.

HTML:

<!-- fixed header -->
    <header id="navbar-top">
        <div class="pt_navbar">
            <div class="container">
                <div class="row">
                    <div class="col-lg-12">
                        <!-- start menu-->
                        <div id="main-nav">
                            <a href="#" id="toggle-nav"><i class="fa fa-bars"></i> Miracle Trainer</a>
                            <ul class="pt_nav nav">
                                <li class="active">
                                    <a href="#welcome">Welcome</a>
                                </li>
                                <li>
                                    <a href="#portfolio">Training Videos</a>
                                </li>
                                <li>
                                    <a href="#pricing">Pricing</a>
                                </li>
                                <li>
                                    <a href="#contact">Contact</a>
                                </li>
                            </ul>
                        </div>
                        <!-- end menu-->
                    </div>
                </div>
            </div>
        </div>
    </header>

JS:

I need a way to close the toggle-nav when a menu is selected.

$("body").on('click', '#toggle-nav', function(e){
        e.preventDefault();

        var nav_menu = $("#navbar-top .pt_navbar ul");

        if( nav_menu.height() < 10 ){
            nav_menu.addClass('open_menu');
        }else{
            nav_menu.removeClass('open_menu');
        }
});

I am currently using this for a slide-out menu:

$('.slideout-menu-toggle, .select').on('click', function(event){
    event.preventDefault();
        // create menu variables
    var slideoutMenu = $('.slideout-menu');
    var slideoutMenuWidth = $('.slideout-menu').width();
        // toggle open class
    slideoutMenu.toggleClass("open");
        // slide menu
    if (slideoutMenu.hasClass("open")) {
        slideoutMenu.animate({
        right: "0px"
        });
    } else {
        slideoutMenu.animate({
        right: -slideoutMenuWidth
        }, 400);
    }
});

Some adjustments might work for you.

EDIT: with the above working code in mind, I think your first jQuery line should be like this:

$('#toggle-nav, .select').on('click', function(e){

and add the "select" class to your list items.

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