jQuery Highlight Navigation Menu v.02 Script

I have found a simpler way to add class=”selected” to any navigation menu by checking your URL path against links on the page. I’ve only tested this with page slugs in wordpress. But it works very nicely.

// Highlight Tab v.02 by Jake Rutter
// Website: http://www.onerutter.com
// Feel free to use and adapt, please just give credit where credit is due.
 
        jQuery(document).ready(function(){
             var path = location.pathname;           
              jQuery("a[href$='" + path + "']").addClass("selected");
     });

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

7 Responses to “jQuery Highlight Navigation Menu v.02 Script”

7 Comments so far
  1. are you using superfish or?
    I'd like to see some source files.

    Thanks!

  2. Hi, thanks for the script, I just have one problem. On the homepage all the menu items get class selected…how to select just "Home"?

  3. I found this solution to my previous comment –

    jQuery(document).ready(function(){
    var path = location.pathname;
    if(location.pathname != "/") {
    jQuery("a[href$='" + path + "']").addClass("current");
    } else $('#menu a:eq(1)').addClass('current');
    });

  4. Anonymous Coward

    August 5th, 2009 at 3:02 pm

    This works great if there already is no class attribute set. But my link already has an attribute. For example class="someclass", and this snippet doesn't make it class="someclass selected", which is what I want. Would that be possible? This snippet was great help for me and I am not very fluent in javascript.

  5. This is not working in IE 6, pls tell how to make it work in IE6

  6. I have an issue with the script. In IE6, the script is not working. How to solve it ?

  7. one more solution from my side
    jQuery(document).ready(function(){
    var file_name = document.location.href;
    var end = (file_name.indexOf("?") == -1) ? file_name.length : file_name.indexOf("?");
    jQuery("a[href='" + file_name.substring(file_name.lastIndexOf("/")+1, end) + "']").addClass("selected");
    });




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 a perpetual license to reproduce your words and name/web site in attribution. Inappropriate comments will be removed at admin's discretion.