Highlight current menu item in JQuery

21 Aug 2016

Having issues highlighting your current navigation menu item? JQuery makes it easy in just a few lines of code. Here’s a copy-pasta for you.

If you have a standard menu/navigation layout like below, copy the stuff between the ‘script’ tags and stick it somewhere close to the your navigation element.

I initially had the script executing at the bottom of the page, however there was a noticeable flash when navigating through the pages.

  <nav>
    <ul>
      <li><a href="http://www.codestub.com/about">About</a></li>
      <li><a href="http://www.codestub.com/portfolio">Portfolio</a></li>
      <li><a href="http://www.codestub.com/blog">Blog</a></li>
      <li><a href="http://www.codestub.com/contact">Contact</a></li>
    </ul>
  </nav>

  <script>
    $('nav a').each(function() {
      if ($(this).attr("href") == window.location.pathname) {
        $(this).attr("id", "active");
      }
    });
  </script>

All this does is go through each ‘a’ within my ‘nav’ element and if the URL of the link is equal to the current window URL, then it sets the id attribute to active.

Note: you will need to add some style for your new id tag e.g.

  #active {
    color: #29bbb0;
  }