How To Close Bootstrap Navbar After Click?

-

Problem: Bootstrap Navbar Stays Open After Clicking

The Bootstrap navbar is a common navigation component, but it can stay open after a link is clicked on mobile devices. This can confuse visitors and block the view of the page content. Closing the navbar automatically after a link is clicked would improve user experience and site navigation.

Solutions for Closing Bootstrap Navbar

Using JavaScript Event Listeners

To close the Bootstrap navbar after clicking a link, you can add click event listeners to the navbar links. This method uses JavaScript to detect when a link is clicked and then closes the navbar.

Here's a code snippet that shows this approach:

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')) {
        l.addEventListener('click', () => { 
            bsCollapse.toggle() 
        })
    }
})

This code selects all navbar links, adds a click event listener to each, and toggles the navbar collapse when a link is clicked. The bootstrap.Collapse.getOrCreateInstance() method controls the navbar's collapse behavior.

Tip: Prevent Default Behavior

To prevent the default behavior of the link (e.g., navigating to a new page) when closing the navbar, you can add event.preventDefault() to your click event handler:

l.addEventListener('click', (event) => {
    event.preventDefault();
    bsCollapse.toggle();
})

This can be useful if you want to close the navbar before navigating to the new page or if you're using single-page application routing.

Implementing Data Attributes

Another method to close the Bootstrap navbar after clicking a link is to use Bootstrap's built-in data attributes. This approach doesn't need JavaScript and uses Bootstrap's own functionality.

To use this method, add data-bs-toggle="collapse" and data-bs-target=".navbar-collapse.show" to each navbar link:

<ul class="navbar-nav me-auto">
    <li class="nav-item active">
        <a class="nav-link" href="#" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Home</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="#" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Link</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="#" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">Another Link</a>
    </li>
</ul>

These data attributes tell Bootstrap to toggle the collapse state of the navbar when a link is clicked. The .navbar-collapse.show selector targets the open navbar, closing it when a link is selected.

Both methods improve the user experience on mobile devices by closing the navbar after a link is clicked.