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


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!
120x20 thumb black Jquery Super Tip! Automatically highlight the links/menu of the current page with 1 line of code

Some links that you might find useful [External]:

Related posts:

  1. Super Tip! How to Create that floating Facebook toolbar at the bottom of the page!
  2. How to: Fix OCUpload/One-Click Upload clicking bug in IE7 & IE8 (jquery)

Still can't see what you're looking for?



22 Responses to “”

  1. argh… secret weapon huh!

  2. tartel on August 29th, 2009 at 6:51 AM
  3. 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. Alex on October 14th, 2009 at 10:20 PM
  5. 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.

  6. Alex on October 14th, 2009 at 10:21 PM
  7. 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!

  8. Cyber Valdez on October 16th, 2009 at 12:20 AM
  9. 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.

  10. Alex Bloom on October 16th, 2009 at 1:16 AM
  11. 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.

  12. Alex on October 16th, 2009 at 1:29 AM
  13. 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.

  14. Alex on October 16th, 2009 at 1:58 AM
  15. 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?

  16. Cyber Valdez on October 16th, 2009 at 11:54 PM
  17. 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.

  18. alex on October 23rd, 2009 at 6:51 AM
  19. Cool! Nice to see that worked for you =)

  20. Cyber Valdez on October 26th, 2009 at 10:44 AM
  21. Awesome, works a treat. Saved me some hassle with css. Thanks

  22. Dave on January 2nd, 2010 at 8:10 PM
  23. 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

  24. Glennyboy on April 6th, 2010 at 8:52 PM
  25. 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!

  26. Cyber Valdez on April 7th, 2010 at 12:24 AM
  27. 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

  28. Glennyboy on April 7th, 2010 at 6:24 PM
  29. 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

  30. Glennyboy on April 9th, 2010 at 2:46 AM
  31. 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

  32. Cyber Valdez on April 9th, 2010 at 4:24 AM
  33. Hi
    This looks excellent – I’ll give it a whirl and let you know how I got on!
    Cheers
    Glennyboy

  34. Glennyboy on April 9th, 2010 at 4:33 AM
  35. 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

  36. Glennyboy on April 15th, 2010 at 10:41 PM
  37. 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.

  38. Cyber Valdez on April 16th, 2010 at 3:39 AM
  39. 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

  40. Glennyboy on July 20th, 2010 at 11:10 PM
  41. 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.

  42. Cyber Valdez on July 21st, 2010 at 2:11 AM
  43. Hi
    Would you mind demonstrating that please.
    Thanks
    Glennyboy

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

Leave a Reply

Anti-Spam Protection by WP-SpamFree