Trying to close a hamburger menu when it is clicked on

Hi all

I am making a web page for a friend, responsive, using bootstrap 5. I have a navbar that goes down to a hamburger menu when the window is small, such as on a phone. When I click on the menu icon, it displays the menu and clicking on the items works. However, after you click on the menuitem, I expect the menu to collapse back. I actually found an article on this in the html forum, but it does not work. the answer was to put the following code at the end of my body area:

  <script>
$("#navbarSupportedContent a:not(.dropdown-toggle)").click(function() {
  $("#navbarSupportedContent").collapse("hide");
});
I am unable to paste my nav code in to this text input....

Any ideas as to my mistake? I am new to this, so be kind!

Thanks

Cyndi

Bootstrap5 doesn’t use jquery (your code above is jquery) I believe so you would either have to add jquery and re-test or use a custom vanilla js routine.

I have an old demo here that has some code added to do what you want but there may be better ways to do this,

This was the standard bootstrap code but with this extra js added added at the bottom of the html.

 document
      .querySelectorAll(".navbar-nav li a:not(.dropdown-toggle)")
      .forEach((link) => {
        link.addEventListener("click", () => {
          const navbarResponsive = document.getElementById(
            "navbarSupportedContent"
          );
          if (navbarResponsive.classList.contains("show")) {
            const navbarToggler = document.querySelector(".navbar-toggler");
            setTimeout(() => {
              navbarToggler.click();
            }, "1000");
          }
        });
      });

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.