jQuery Highlight Navigation Menu v.01 Script

A few months ago, I created a little script using the jQuery library which will add class=”current” to tabs, allowing you to highlight your menu for you users. Its pretty basic, but it searches the URL, if it finds a match with the link that was clicked – then it add’s class=”current” to that particular tab. You can then use that class in your css, to make a highlighted state.

Here is the code:

// Highlight Tab v.01 by Jake Rutter
// Website: http://onerutter.com
// Feel free to use and adapt, please just give credit where credit is due.

// ----------- highlight tab function -----------
    var path = location.pathname;

    var home = "/";
    $("a[href='" + [ path ] + "']").parents("li").each(function() {

Feel free to adapt and use this code on your site, I would appreciate it if you could leave my comments in as the creator in the .js file. If you are unfamiliar with how jQuery works, you can read this tutorial which will get you up to speed!


8 thoughts on “jQuery Highlight Navigation Menu v.01 Script”

  1. Hi, thanks for your script.

    Couple of things needed to be changed in order for it to work.

    Firstly, don’t think the square brackets around the path are necessary i.e. [ + path + ]

    Secondly, I found it useful to use the ‘ends with syntax for matching the path i.e instead of “a[href=’ + path I used “a[href $=’ + path

    see docs at http://docs.jquery.com/Selectors/attributeEndsWith#attributevalue

    anyway, it’s live and working on a site I did, http://www.worldmarathonchallenge.com

  2. Hi, thanks for the code. Unfortunately I can't get it to work. I tried Pauls version from his live site but unfortunately can't get it to work either.

    I used:

    var path = location.pathname;
    $("a[href $='" + path + "']").parents("li").each(function() {

    and am linking to the lattest JQuery. I have my main nav within a container and the UL has an id of 'nav'.

    Any help or advice is greatly appreciated.

    1. Hi Dan
      Think your just mising your closing brackets. I've used the code below and it seems to work.
      <script language="javascript" type="text/javascript">
      var path = location.pathname;
      $("a[href $='" + path + "']").parents("li").each(function() {

  3. You have to make sure that in your CSS, the "current" class is changing the LI of the link… if your CSS is telling the A tag to use "current", then remove the: .parents("li") section of the script. That way, you are telling the script to find all of the a tags that match the path, then apply the current class to that, rather than it's LI tag.

    Hope that helps.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: