Unless I’m missing something, it seems like Bootstrap still does not recognize the need to collapse the mobile menu when you have a one page website where the menu items link to anchor links on the same page.
This issue was brought up and addressed in this forum post way back in 2018 where @saj provided an effective (though somewhat laborious) solution involving some JavaScript and the adding of data attributes to all the anchors and links.
I’ve noted that the BSS New Age template is a one-page site with anchor links and it contains the below JavaScript that handles the collapsing of the mobile menu when clicking a menu link, and doesn’t require adding any data attributes.
(function() {
"use strict"; // Start of use strict
var mainNav = document.querySelector('#mainNav');
if (mainNav) {
var navbarCollapse = mainNav.querySelector('.navbar-collapse');
if (navbarCollapse) {
var collapse = new bootstrap.Collapse(navbarCollapse, {
toggle: false
});
var navbarItems = navbarCollapse.querySelectorAll('a');
// Closes responsive menu when a scroll trigger link is clicked
for (var item of navbarItems) {
item.addEventListener('click', function (event) {
collapse.hide();
});
}
}
// Collapse Navbar
var collapseNavbar = function() {
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
if (scrollTop > 100) {
mainNav.classList.add("navbar-shrink");
} else {
mainNav.classList.remove("navbar-shrink");
}
};
// Collapse now if page is not at top
collapseNavbar();
// Collapse the navbar when page is scrolled
document.addEventListener("scroll", collapseNavbar);
}
})(); // End of use strict
The problem though is that this script won’t work on a site built from scratch because the New Age template apparently references a class (.navbar-shrink
) that is not present in the standard bootstrap.min.css file (I presume it uses a custom bootstrap.min.css). While I could probably dig through the css and extract the .navbar-shrink
class, I’m thinking there must be an easier way.
I found the following JQuery solution online which works perfectly with a mere three lines of code, but of course it requires loading JQuery, which is obviously undesirable in a Bootstrap 5.x site.
$('.navbar-nav>li>a').on('click', function(){
$('.navbar-collapse').collapse('hide');
});
I’m a total JS novice, so I’m wondering if anybody with JS experience would know of a way to do what this JQuery script is doing using plain JavaScript?