Search code examples
htmlbootstrap-5

Close offcanvas menu after click anchor links


The problem was that the offcanvas menu stayed open by clicking an anchor link. To close the menu after click I use the following code for an onclick event:

function close_offcanvas() {
            var element1 = document.getElementById("eff_nav_toggler");
            element1.classList.remove("collapsed");
            var element2 = document.getElementById("navbarSupportedContent");
            element2.classList.remove("show");
            document.getElementById("eff_nav_toggler").setAttribute('aria-expanded', 'false');
}

Here is the HTML Code:

<nav class="navbar navbar-expand-lg navbar-light bg-white fixed-top eff-main-navbar">
    <div class="container-fluid">
        <a class="navbar-brand" href="<?php echo ROOT_DIR ; ?>/index.php">
            <img src="<?php echo ROOT_DIR ; ?>/assets/images/logo/logo-klein_170.jpg" alt="Logo" title="Logo">
        </a>
        <button 
            id="eff_nav_toggler"
            class="navbar-toggler"  
            type="button" 
            data-bs-toggle="collapse"  
            data-bs-target="#navbarSupportedContent"   
            aria-controls="navbarSupportedContent"  
            aria-expanded="false"  
            aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav mx-auto mb-2 mb-lg-0 w-100 ps-5">
                <li class="nav-item d-flex align-items-center"><a class="nav-link" href="<?php echo ROOT_DIR ; ?>/index.php#link1" onclick="close_offcanvas()">Link 1</a></li>
                <li class="nav-item d-flex align-items-center"><a class="nav-link" href="<?php echo ROOT_DIR ; ?>/index.php#link2" onclick="close_offcanvas()">Link 2</a></li>
            </ul>
        </div>
    </div>
</nav>

It is working fine. But I am not sure if this is the best solution. Any other ideas?


Solution

  • No need to do the hard things. bootstrap has attribute called

    data-bs-dismiss="offcanvas"
    

    Add this attribute to your anchor tag or li tag. it will close offcanvas on click