Problem:
You have a Bootstrap navbar that collapses on mobile devices, but you want it to close when users click on links.
Solution:
Bootstrap 5 (beta)
const navLinks = document.querySelectorAll('.nav-item') const menuToggle = document.getElementById('navbarSupportedContent') const bsCollapse = bootstrap.Collapse.getOrCreateInstance(menuToggle, {toggle: false}) navLinks.forEach((l) => { if (menuToggle.classList.contains('show')) { // only fire on mobile l.addEventListener('click', () => { bsCollapse.toggle() }) } })
Data Attribute Method: Add data-bs-toggle="collapse" and data-bs-target=".navbar-collapse.show" attributes to links.
<nav> <ul> <li> <a href="#" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Home</a> </li> ... </ul> </nav>
Bootstrap 4
<ul class="navbar-nav mr-auto"> <li data-toggle="collapse" data-target=".navbar-collapse.show"> <a href="#home">Home</a> </li> ... </ul>
$('.navbar-nav>li>a').on('click', function(){ $('.navbar-collapse').collapse('hide'); });
<ul> <li> <a href="#" data-toggle="collapse" data-target=".navbar-collapse.show">Home</a> </li> ... </ul>
Bootstrap 3
<ul> <li data-toggle="collapse" data-target=".navbar-collapse.show"> <a href="#home">Home</a> </li> ... </ul>
$('.navbar-nav>li>a').on('click', function(){ $('.navbar-collapse').collapse('hide'); });
The above is the detailed content of How to Automatically Close a Bootstrap Navbar After Clicking a Link?. For more information, please follow other related articles on the PHP Chinese website!