Jquery Super Tip! Automatically highlight the links/menu of the current page with 1 line of code

| 25 Comments »

One very important usability feature of a website is to have the menu or links highlight the current page the visitor is currently in. Here’s a trick I do with jquery to do just about that. For educational purposes, i’ve split it to 3 lines of code to make it more understandable.

Simply add the following to your header (don’t forget to include jquery first!).

$(document).ready(function()   {     var loc = window.location.toString().split("/")     loc = loc[loc.length – 1]     $("#navigation li a[href=\""+loc+"\"]").addClass("selected");   });

Of course, jquery isn’t really needed to do this. If you prefer to have it done _without_ jquery, here’s a native way of doing things:

   window.onload = function()    {      var current_page = window.location.toString().split("/")[window.location.toString().split("/").length – 1]      var links = document.getElementsByTagName("a");      for (x in links)      {        var link = (links[x].href != undefined) ? links[x].href.toString().split("/")[links[x].href.toString().split("/").length – 1] : ""        if (link == current_page)          links[x].className = (links[x].className == "") ? "selected" : links[x].className + " selected"      }    }

_Important_: The above code takes use of the .selected class. Simply add the class to your a:hover classes.

#navigation ul li a:hover { color: #ff0; }

Should be written as:

#navigation ul li a:hover, #navigation ul li a.selected { color: #ff0 !important; }

_Don’t Forget!_, this works for menu/links with background images as well.

and that’s all there is to it! Don’t forget to thumb this up and share!


25 Comments on “Jquery Super Tip! Automatically highlight the links/menu of the current page with 1 line of code”

  1. 1 tartel said at 6:51 AM on August 29th, 2009:

    argh… secret weapon huh!

  2. 2 Alex said at 10:20 PM on October 14th, 2009:

    hey mate, ive tried both methods and neither are working. on my computer, i dont think its passing the ‘selected’ property, because it changes the link correctly when hovering, but not when ‘selected’. any ideas? could my external css with a, body, and any other tags be affecting it? cheers, alex.

  3. 3 Alex said at 10:21 PM on October 14th, 2009:

    hey mate, ive tried both methods and neither are working. on my computer, i dont think its passing the ’selected’ property, because it changes the link correctly when hovering, but not when ’selected’. any ideas? could my external css with a, body, and any other tags be affecting it? cheers, alex.

  4. 4 Cyber Valdez said at 12:20 AM on October 16th, 2009:

    Hi Alex, your best bet is to put: !important after the css attribute/properties’ value, this will make the value a priority thus preventing any other css from changing it.

    ex:

    navigation ul li a:hover, #navigation ul li a.selected { color: #ff0 !important; }

    hope that helps!

  5. 5 Alex Bloom said at 1:16 AM on October 16th, 2009:

    Hey, Ive tried the above method, and I’ve made a few other changes (ive made your jquery function external), and it is working on all but the second menu item (issues). Are you able to see (and help me fix) the problem? Thanks again, Alex.

  6. 6 Alex said at 1:29 AM on October 16th, 2009:

    Hey, I’ve found that if I delete references to other jquery javascripts it works fine.. do you know how I can stop them interfering? Thanks, Alex.

  7. 7 Alex said at 1:58 AM on October 16th, 2009:

    Hey, sorry to bombard you, but I’ve just gone with inline styles for that element only.. seems the easiest way to do it, and its valid with W3. ISSUES

    I found the js interference file and its too dense for me. Thanks for your help and of course the script! Alex.

  8. 8 Cyber Valdez said at 11:54 PM on October 16th, 2009:

    well that’s weird, maybe I should take a look at your website, do you have the url so I can take a look at it?

  9. 9 alex said at 6:51 AM on October 23rd, 2009:

    hey, its steindependent.com and i eventually got it going. thanks heaps. it was simply that one of the other scripts was changing (or doing something) with the $, once I changed the $() to jQuery() it worked perfectly, and that has fixed a lot of other interference problems too. thanks. alex.

  10. 10 Cyber Valdez said at 10:44 AM on October 26th, 2009:

    Cool! Nice to see that worked for you =)

  11. 11 Dave said at 8:10 PM on January 2nd, 2010:

    Awesome, works a treat. Saved me some hassle with css. Thanks

  12. 12 Glennyboy said at 8:52 PM on April 6th, 2010:

    Hi I’ve tried all ways to do this and can’t seem to get it working here:-http://www.allhomegrown.com/menu.php Given that menu.php is the active page I would hope to see the text in red as per my ‘active class’?

    Code and styles all on page…

    Any insights greatly appreciated! Cheers Glennyboy

  13. 13 Cyber Valdez said at 12:24 AM on April 7th, 2010:

    Hi Glenn, try doing an alert(loc) at the end of the $(document).ready() script, your url’s href must match the same text for it to work. You should be able to fix your problems by removing the forward slash in your links’ hrefs. Hope that helps!

  14. 14 Glennyboy said at 6:24 PM on April 7th, 2010:

    Hi Thanks for the quick input… not sure what you mean by ‘alert(lo), but removing the leading ‘/’ indeed did work.

    Ultimately though I need this to work under a mod-rewrite and I need to use absolute links with the leading /. How can I achieve this as per:-

    http://www.allhomegrown.com/menu/

    With rewritten link as second line down and being Menu Mod Rewrite

    Any ideas?

    Glennyboy

  15. 15 Glennyboy said at 2:46 AM on April 9th, 2010:

    Hi Again

    Great so far, but any ideas how this will work after mod-rewrite anyone:-

    http://www.allhomegrown.com/menu/

    Second link down ‘Menu Mod Rewrite’ should show as current acive in ‘red’.

    Cheers

    Glennyboy

  16. 16 Cyber Valdez said at 4:24 AM on April 9th, 2010:

    hi Glenny, you have 3 options option 1:

    var loc = window.location.toString().split(“/”) loc = loc[loc.length – 2] $(‘.CollapsiblePanelRepeat a[href=”/’+loc+’/”]’).addClass(“selected”);

    the format of your urls links should be (note the forward slash at the end.) <a href=”/menu/” rel=”nofollow”>

    option 2: same as above but no forward slash in your urls

    var loc = window.location.toString().split(“/”) loc = loc[loc.length – 2] $(‘.CollapsiblePanelRepeat a[href=”/’+loc+'”]’).addClass(“selected”);

    the format of your urls links should be (note the forward slash at the end.) <a href=”/menu” rel=”nofollow”>

    option 3: Exact addresses.

    var loc = window.location.toString() $(‘.CollapsiblePanelRepeat a[href=”‘+loc+'”]’).addClass(“selected”);

    the format of your urls links should be: <a href=”http://www.allhomegrown.com/menu/” rel=”nofollow”> <a href=”http://www.allhomegrown.com/menu/menu.php” rel=”nofollow”>

    p.s: if you plan on copying the codes above, use this link instead. This blog theme seems to be converting the apostrophes and quotes so copy pasting the codes from this blog won’t work. Here’s the raw version: http://pastebin.com/hBywpeBE

  17. 17 Glennyboy said at 4:33 AM on April 9th, 2010:

    Hi This looks excellent – I’ll give it a whirl and let you know how I got on! Cheers Glennyboy

  18. 18 Glennyboy said at 10:41 PM on April 15th, 2010:

    Hi So far so good… almost!!! I have this working on my test page here:-http://www.allhomegrown.com/menu/ … but I can’t get it working on my actual menu here:-http://www.allhomegrown.com/product/1/ I think this may be because I’m going a further child level down in the url and perhaps the code needs to reflect this as ‘/product/id/’ I am using your option 1 and this is my code:-

    $(document).ready(function() { var loc = window.location.toString().split(“/”) loc = loc[loc.length – 2] $(‘.CollapsiblePanelRepeat a[href=”/’+loc+’/”]’).addClass(“active”);

    });

    and this is my link:-

    <a href="/product//”>

    Any ideas my man? Glennyboy

  19. 19 Cyber Valdez said at 3:39 AM on April 16th, 2010:

    try replacing loc = loc[loc.length – 2] to loc = loc[loc.length – 2] + loc[loc.length – 1] you should try doing an alert(loc) after that as well so you can see what’s wrong with your url. your url should have the same address as the alerted string.

  20. 20 Glennyboy said at 11:10 PM on July 20th, 2010:

    Hey, Long time

    Unfortunately I never could get the concept above working on my configuration (ssi + mod-rewrite).

    I have found something in the JQuery docs which tries to get the same result:-

    $(function(){ var path = location.pathname.substring(1); if ( path ) $(‘#nav li a[href$=”‘ + path + ‘”]’).attr(‘class’, ‘selected’); });

    Unlike your script the problem with this is that it doesn’t strip anything out and takes a very literal link strategy.

    So on my current development site:-

    http://ps.slickmedia.co.uk/

    I get nothing on the straight url, but if I visit:-

    http://ps.slickmedia.co.uk//

    Then all my nav items get the ‘selected class’ as they all start and end with a ‘/’ (e.g. ‘/’, /’about_us/, ‘/contact_us/’ etc) as per your option 1 above. So currently this script is just searching for a ‘/’ and then applying the class.

    Obviously I don’t want that and I’m thinking that if we can combine this script with yours we may have a solution to my problem of it not applying. And that’s where I’m stuck. Any ideas?

    Glennyboy

  21. 21 Cyber Valdez said at 2:11 AM on July 21st, 2010:

    Hmm the technique should also work with SSI+Rewrites setup, as for your script, you may want to use lastIndexOf(‘/’) to omit any extra slashes at the end though.

  22. 22 Glennyboy said at 5:52 PM on July 21st, 2010:

    Hi Would you mind demonstrating that please. Thanks Glennyboy

  23. 23 Rose said at 2:09 AM on August 14th, 2010:

    Your script was just what I needed! Thank you.

    I do have a few questions though I hope you can help me with. I’m just learning jquery and can’t seem to figure out how to add to this script so that line items with ul submenus that are active are automatically expanded on my accordion. I have a class called “expand” that I would like added through jquery.

    Here’s an example of my current nav structure:

    <a href=”#” rel=”nofollow”>Category 1</a> <a href=”#”>Category 2</a>

    <a href=”#” rel=”nofollow”>Subcategory 1</a> <a href=”#” rel=”nofollow”>Sub 2</a>

    If an item in ul.submenu is active, I’d like the parent li of the ul to automatically have the “expand” class added to it. Any suggestions you have would be great. Thanks.

  24. 24 Cyber Valdez said at 3:50 AM on August 14th, 2010:

    Hi Rose, try something like: $(“#navigation li a[href=\””+loc+”\”]”).addClass(“selected”).parent().addClass(“expand”);

    (just add as many .parent() you need until you get to the right one) $(“#navigation li a[href=\””+loc+”\”]”).addClass(“selected”).parent().parent().addClass(“expand”);

    Hope this helps!

  25. 25 Fred Riley said at 8:11 PM on August 23rd, 2010:

    Thanks, that’s a really handy and very simple bit of code, which works a treat :)


Leave a Reply