Active navigation link with javascript / jQuery

Navigation is something that almost every web app has to deal with, and most of the time navigation will have an active state. There are a couple of ways to do this, and I am going to demonstrate using ¬†jQuery as well as plain javascript just in case you don’t have jQuery in your project.

Bootstrap Navigation

So lets take a look at a normal bootstrap navigation


Setting active navigation

What we want to do is get the current url, and then loop through each menu item and check to see if the href is equal to the url. We also want to check if the if the menu item is part of a dropdown menu, if it we want to find the parent menu item and set it to active as well. Here is what the javascript looks like.

$().ready(function(){
  setActiveLink();
});


function setActiveLink(){

  // get the current url
  var url = window.location.pathname;
  // decode the url
  url = decodeURIComponent(url);

  // this is incase your project isn't in the root directory of your url
  // for example localhost/ActiveNavLink/index.html
  projectPrefix = "/ActiveNavLink/";

  // loop through each nav li
  $('.nav li').each(function(){

    // get the menu a tag and get its href attribute
    var href = $(this).find('a').attr('href');

    // href can be undinded if there is a divider
    if(href === undefined)
      return;

    // add the project prefix
    href =  projectPrefix + href;
    
    // check if the menu item is equal to the current url    
    if(url.substring(0, href.length) == href){
      // set active class to li
      $(this).addClass('active');

      // check if there is a parent dropdown
      var parentDropDown = $(this).closest('.dropdown');
      // if there is a parent dropdown set it to active as well
      if(parentDropDown !== undefined){
        parentDropDown.addClass('active');
      }
    }
      
  });

}

Screen Shot 2014-02-11 at 2.49.55 PM
If you want to take a look at a working demo take a look at https://github.com/barrettbreshears/ActiveNavLink. You will probably need to change minor details to make this work in your project, but its pretty straight forward. Hope this is helpful!