Close BootStrap nav menu after click
By Riley BrownAugust 5, 2018
I found an interesting snippet on StackOverflow a while back when I was trying to find a solution to close a bootstrap mobile nav after a click. I’m not sure why this is not built into BootStrap, but it is a pretty easy fix.
// script to close mobile menu after click
$(".navbar-collapse a").click(function(e) {
if (
$(e.target).is("a") &&
window.innerWidth < 767 &&
$(e.target).attr("class") != "dropdown-toggle"
) {
$(".navbar-collapse").collapse("toggle")
}
})
This jQuery script will target every a tag in the nav, and collapse the menu after it is clicked. I have mine to include a window width of 767px, but you if need it higher or lower you can simply change to what you need.