How to automatically close a mobile menu when item is clicked?

Viewed 241

I have a one page responsive site and everything works okay but I would like to be able to automatically close the mobile menu once an item is clicked. Currently I have to do this manually can anyone please help me with this? - it's driving me round the bend.

\\ my html

<button class="navbar-toggle">
    <i class="fa fa-bars"></i>
</button>

\\ my js

// Mobile nav toggle
$('.navbar-toggle').on('click',function() {
    $('.main-nav').toggleClass('open');
});

\\

Any help with this would be greatly appreciated - thank you. (I am using bootstrap 3.3.7) if that also helps

2 Answers

If you need to close it on link click you could use something like this:

// maybe would be better to indicate menu link class explicitly instead of using just 'a'
$('.navbar-toggle a').on('click',function() {
    $('.main-nav').removeClass('open');
});

Try the following:

    $('.main-nav').on('click', function () {
        $(this).toggleClass('open');
    });

Although I can't see your HTML but I believe your#main-nav is a container for the menu items. When an item is clicked, the event will bubble through the container and the container will change state appropriately.

Related