Bootstrap Dropdown Menu without Bootstrap JS

by Jimmy Chandra

HTML

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>
  <body>
    <div class="navbar navbar-default" role="navigation">
      <div class="container-fluid">
        <div class="navbar-header">
        </div>
        <div class="navbar-collapse collapse" id="navbar-main">
          <ul class="nav navbar-nav">
            <li><a href="/Home/EnterpriseDashboard"><span class="glyphicon glyphicon-home"></span> Home</a></li>
            <li class="dropdown">
              <a class="dropdown-toggle clickable" data-toggle="dropdown"><span class="glyphicon glyphicon-th"></span> Manage <span class="caret"></span></a>

              <ul class="dropdown-menu multi-level" role="menu">
                <li><a href="/subscription/rules"><span class="glyphicon glyphicon-cog"></span> Rules</a></li>
                <li><a href="/subscription/sync"><span class="glyphicon glyphicon-repeat"></span> Data Sync</a></li>
                <li><a href="/subscription/masterrules"><span class="glyphicon glyphicon-check"></span> InvoiceSmash Setup</a></li>
              </ul>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </body>
</html>

CSS

a.clickable {
  cursor: pointer
}

JavaScript

document.addEventListener('DOMContentLoaded', () => {

  // 1. Attach a click handler to every `.dropdown-toggle`
  document.querySelectorAll('.dropdown-toggle').forEach(toggle => {
    const parentLi = toggle.closest('.dropdown');

    toggle.addEventListener('click', e => {
      e.preventDefault();                    // keep the link from navigating
      e.stopPropagation();                   // don’t bubble to document yet
      parentLi.classList.toggle('open');     // show/hide this menu
    });
  });

  // 2. Clicking anywhere else closes *all* open menus
  document.addEventListener('click', () => {
    document.querySelectorAll('.dropdown.open')
            .forEach(d => d.classList.remove('open'));
  });

  // 3. Optional: ESC key closes the current open menu
  document.addEventListener('keydown', e => {
    if (e.key === 'Escape') {
      document.querySelectorAll('.dropdown.open')
              .forEach(d => d.classList.remove('open'));
    }
  });
});