jQuery Highlight Navigation Menu v.01 Script

8

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() {
        $(this).addClass("selected");
    });

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!

[download#4]

  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:

    $(document).ready(function(){
    var path = location.pathname;
    $("a[href $='" + path + "']").parents("li").each(function() {
    $(this).addClass("current");
    });

    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.

    • 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">
      $(document).ready(function(){
      var path = location.pathname;
      $("a[href $='" + path + "']").parents("li").each(function() {
      $(this).addClass("current");
      });
      })
      </script>

  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