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://www.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!

jQuery Highlight Script (1005)

5 Responses to “jQuery Highlight Navigation Menu v.01 Script”

5 Comments so far
  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. Excellent, Im glad I could help you out. Im going to try the ‘ends with syntax’ too. The attribute stuff in jQuery is pretty powerful.

  3. i have an issue with this script as this is not working fine in IE6, what may be the issue

  4. Great stuff. Thanks

  5. 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.




XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

By submitting a comment here you grant Jake Rutter – Front-End Developer and Designer, CSS, JavaScript and jQuery, PHP, Wordpress, Expression Engine, Magento a perpetual license to reproduce your words and name/web site in attribution. Inappropriate comments will be removed at admin's discretion.