Home >Web Front-end >CSS Tutorial >How to Automatically Close a Bootstrap Navbar After Clicking a Link?

How to Automatically Close a Bootstrap Navbar After Clicking a Link?

Barbara Streisand
Barbara StreisandOriginal
2024-12-13 18:23:10442browse

How to Automatically Close a Bootstrap Navbar After Clicking a Link?

How to Close Bootstrap Navbar on Link Click

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)

  • JavaScript Method: Add a click event listener to menu items to toggle the navbar collapse.
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

  • jQuery Method: Use the collapse method on the navbar-collapse element.
<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');
});
  • Data Attribute Method: Add data-toggle="collapse" and data-target=".navbar-collapse.show" attributes to links.
<ul>
    <li>
        <a href="#" data-toggle="collapse" data-target=".navbar-collapse.show">Home</a>
    </li>
    ...
</ul>

Bootstrap 3

  • Data Attribute Method: Add data-toggle="collapse" and data-target=".navbar-collapse.show" attributes to links.
<ul>
    <li data-toggle="collapse" data-target=".navbar-collapse.show">
        <a href="#home">Home</a>
    </li>
    ...
</ul>
  • jQuery Method: Use the collapse method on the navbar-collapse element.
$('.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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn