user3364730 user3364730 - 1 month ago 10
CSS Question

How to Close toggle menu when clicking navigation item anchor link

Please see my FIDDLE

I've got a 1 page website with a "responsive" navigation menu (with anchor links to elements on the page) that prepends to a menu icon when the browser viewport is smaller than a specific width (in my case 767px) using this javascript:

jQuery(document).ready(function($){
$('#menu_wrapper').prepend('<div id="menu-icon">Menu</div>');
$("#menu-icon").on("click", function(){
$("#menu").slideToggle();
$(this).toggleClass("active");
});
});


As you can see in the fiddle I'm also using javascript to make the navigation sticky when scrolling down past navigation element regardless of the viewport size.

Now the problem I have is that when I am below the viewport of 767px, I click on the toggle 'MENU' button to open / show the navigation and when I click an option in the menu, the page scrolls to the correct part of the page BUT the menu stays open.

What I want is the menu to close (slide back up) when an option is clicked in the menu (obviously this must only apply when I am below below the viewport of 767px).

How can I do this?

Answer

Just add this in $(document).ready function

$('#menu li').on('click', function(){
        $("#menu").hide();
        $("#menu-icon").removeClass("active");
    });