简体   繁体   中英

How to hide collapsible navbar menu when clicking outside of it (Bootstrap 5)?

I have a collapsible navbar menu:

<div class="collapse navbar-collapse" id="navbarCollapsible">
   .. menu items ..
</div>

I want to hide it whenever a user clicks outside of it (so not just when he clicks the menu button again):

$(document).ready(function() {
    const navbarCollapsible = document.getElementById('navbarCollapsible');    
    $('.container').on("click", function() {
        navbarCollapsible.hide();
    });
});

But I get: Uncaught TypeError: navbarCollapsible.hide is not a function

Edit:

I made it work using the following:

$(navbarCollapsible).collapse("hide");

But how can I do it without jQuery?

I know I am using jQuery here, but I know that it's not required for Bootstrap 5 - so how am I supposed to use the hide method as described in the docs without jQuery?

The error is because navbarCollapsible is a element of the DOM and not a jQuery Object. There is no hide available.

Try this:

$('body').on("click", function() {
  $(navbarCollapsible).hide();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM