Skip to main content

Add Active Navigation Class Based on URL.

(function () {

  /**
   * Add Active Navigation Class Based on URL
   *
   * @example
   * 
   * <nav>
   *   <ul>
   *     <li><a href="/">Home</a></li>
   *     <li><a href="/about/">About</a></li>
   *     <li><a href="/clients/">Clients</a></li>
   *     <li><a href="/contact/">Contact Us</a></li>
   *   </ul>
   * </nav>
   * 
   * $(function() {
   *   $('nav a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');
   * });
   *
   * http://css-tricks.com/snippets/jquery/add-active-navigation-class-based-on-url/
   */
  var nav = document.getElementById('nav'),
    anchor = nav.getElementsByTagName('a'),
    current = window.location.pathname.split('/')[1];

  for (var i = 0; i < anchor.length; i++) {
    if (anchor[i].href == current) {
      anchor[i].className = 'active';
    }
  }

})();