Bootstrap navbar menu does not collapse after clicking

Hello dears; I have got an issue with Bootstrap version 4.5 navbar menu on mobile and small screen mode. I linked navbar links to sections within same page, but when I open the menu and click the link the menu does not collapse and it looks somewhat weird. here is a live example
click here , when small window screen open the toggle and click pediabooks you see that menu is still open and you should click the toggle button again to close it. My question is that how the menu collapse automatically with clicking the links? thanks for your help

This is really a JS question but a quick google finds many similar solutions like this.

Add this snippet of JS before the closing body tag.

<script>
$(".navbar-collapse a").click(function () {
  $(".navbar-collapse").collapse("hide");
});
</script>

Note that if you are doing ‘in page’ linking/scrolling and using a fixed menu then your scroll destination gets hidden under the fixed navigation. You can offset this with a relatively new css property called scroll-margin-top.

e.g. For your PedBooks element you wouild do this:

#PedBooks{scroll-margin-top:5rem;}

You would need to do the same for the other in page links.

1 Like

Thank you so much dear, it solved the problem but it created a new issue, for the dropdown link it does not work with this because when you click the dropdown link it collapses instead of opening the dropdown list. live example is here (only on small widow device the problem is present). so how can I exclude the dropdown link from collapse on click? thank you again

Ah ok try this instead.

  <script>
    $("#navbarSupportedContent a:not(.dropdown-toggle)").click(function() {
      $("#navbarSupportedContent").collapse("hide");
    });
  </script>

If that doesn’t work I’ll move the thread to the JS forum for a more expert answer :slight_smile:

Problem solved, thank you so much I appreciate.

2 Likes

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