Close Bootstrap mobile menu on menu item click

Close Bootstrap mobile menu on menu item click

I use Bootstrap front-end framework as base for developing mobile friendly websites.

Recently, I developed one page website (one pager) with menu on the top taking user to relevant section on page.

All looked great until I tested this on mobile phone and realised that menu does not close when user click on menu item.

Searching Bootstrap documentation eneded up in no joy at all so I decided to write simple vanilla JavaScript to accomplish what was needed to be done.

JavaScript code below manages the behavior of a navigation menu, specifically its collapsing.

  var mainNavigation = document.getElementById("navbarNav");
  var mainNavigationLinks = document.querySelectorAll("a.nav-link");
  var mainNavigationToggler = document.querySelector(".navbar-toggler");
  mainNavigationLinks.forEach(function(e){
    e.addEventListener('click', function (event) {
      mainNavigationToggler.classList.add("collapsed");
      mainNavigation.classList.remove("show");
    })    
  });

Here is a simple breakdown of what the code actually does

Selecting Elements:

Locate the main navigation element and save it in mainNavigation variable

  var mainNavigation = document.getElementById("navbarNav"); 

Finds all links within the navigation menu that have the class nav-link and saves it to mainNavigationLinks variable

  var mainNavigationLinks = document.querySelectorAll("a.nav-link");

Grab the element that triggers the menu’s toggling and save it in mainNavigationToggler variable

  var mainNavigationToggler = document.querySelector(".navbar-toggler"); 

Attaching Event Listeners:

forEach function iterates through each navigation link and adds an event listener to it.

  mainNavigationLinks.forEach(function(e) { ... }); 

Handling Click Events:

addEventListener listens for clicks on each link

  e.addEventListener('click', function (event) { ... }); 

Inside the event listener:

classList.add adds the “collapsed” class to the toggler element

  mainNavigationToggler.classList.add("collapsed"); 

classList.remove removes the show class from the main navigation element

  mainNavigation.classList.remove("show"); 

Overall Functionality:

When a user clicks on any link within the mobile navigation menu, the code visually collapses the menu which hides the menu content avoid obstructing content web page content

Additional Insights:

The code assumes you use Bootstrap 5 navigation menu structure with links and a toggler element as it depends on CSS classes for visual styling and toggling behavior.

Domains and Web Hosting

Maxer domain and web hosting

Virtual server

Get server with Digital ocean