Dynamically Adding Active Class to Bootstrap Navbar

If you are using Bootstrap on a static website, you might have run into the problem of highlighting the active pages on the navbar.

Active pages are highlighted with the active class.

Here is a sample of a Bootstrap Navbar:

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Navbar</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
<div class="collapse navbar-collapse" id="navbarNav">
  <ul class="navbar-nav">
    <li class="nav-item active">
      <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#">Features</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#">Pricing</a>
    </li>
    <li class="nav-item">
      <a class="nav-link disabled" href="#">Disabled</a>
    </li>
  </ul>
</div>
</nav>

Notice how the “Home” link is darker? In the code, you’ll see li class="nav-item active" wrapping the “Home” link. That makes it nice and clear that visitors are on the homepage of your site.

The trouble is, nobody wants to hard-code a slightly different version of the Navbar on to each page of their website, especially if you are using a static site-builder like Jekyll.

We can get around this problem by using a nifty bit of Javascript to dynamically assign the active class to the link for the page we are on.

We can use a bit of javascript to solve this problem. The code below compares the link of the navigational element to the URL of the current page. When they match, the class active is added.

  <script>
    $(document).ready(function () {

          //Cycles through each of the links in the nav
          $('.nav-item a').each(function() {
              //Compares the href of the nav a element to the URL page
              if ($(this).attr('href') == window.location.pathname) {
                  //If they match, add class name to the parent li element
                  $(this).parent().addClass('active');
              }

    });
    });
  </script>
  

Include this at the bottom of the page, after you’ve loaded jQuery. You can see a working example on this site.

Hat Tip: NinjaCSS