Navbars

Closing the mobile menu

How to close the mobile menu when click a link in the menu

document.addEventListener(
  'DOMContentLoaded',
  function () {
    'use strict';
    const navbarCollapse = document.querySelector('.navbar-collapse');
    const mobileMenu = new bootstrap.Collapse(navbarCollapse, { toggle: false });
    const handleMobileMenu = () => mobileMenu.hide();
    document.addEventListener('click', handleMobileMenu);
    document.addEventListener('scroll', handleMobileMenu);
  },
  false
);

Scroll to right place

How to scroll to the right place when click a link in the menu

html {
  scroll-padding-top: 56px; /* the height of the navbar */
}

Off canvas

First drop a Navbar component to your design. Set the navbar to fixedTop or fixedBottom. Give the navbar an Id=mainNav in this case. Set the breakpoint where you want the navbar toggler to be shown in the navbar. Set the navbar toggler to toggle the offcanvas

Closing the offcanvas menu

This is how you close the offcanvas menu when you click on a link in the menu

document.addEventListener(
  'DOMContentLoaded',
  function () {
    'use strict';

    const mainNav = document.querySelector('#mainNav');
    if (mainNav) {
      const navbarCollapse = document.querySelector('.navbar-toggler');
      const menuOffcanvas = document.getElementById('offcanvas-1');
      const toggleNavbarToggler = () => navbarCollapse.classList.toggle('collapsed');

      if (menuOffcanvas) {
        menuOffcanvas.querySelectorAll('a[href^="#"]').forEach((anchor) => {
          anchor.addEventListener('click', (e) => {
            e.preventDefault();
            const anchorLink = anchor.getAttribute(['href']);
            if (anchorLink === '#') return;
            const anchorID = document.querySelector(anchorLink);
            if (anchorID) {
              const position = anchorID.offsetTop - mainNav.offsetHeight;
              window.scrollTo({
                top: position,
                behavior: 'smooth',
              });
              navbarCollapse.click();
            } else console.log(`debug: ${anchorLink} does not exist on the page`);
          });
        });
        menuOffcanvas.addEventListener('hide.bs.offcanvas', () => toggleNavbarToggler());
        menuOffcanvas.addEventListener('show.bs.offcanvas', () => toggleNavbarToggler());

        window.addEventListener('scroll', () => {
          if (menuOffcanvas.classList.contains('show')) {
            navbarCollapse.click();
          }
        });
        window.addEventListener('resize', () => {
          if (menuOffcanvas.classList.contains('show')) {
            navbarCollapse.click();
          }
        });
      }
    }
  },
  false
);