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!
![]()
Related posts:
- Super Tip! How to Create that floating Facebook toolbar at the bottom of the page!
- How to: Fix OCUpload/One-Click Upload clicking bug in IE7 & IE8 (jquery)
Still can't see what you're looking for?










argh… secret weapon huh!
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.
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.
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!
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.
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.
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.
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?
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.
Cool! Nice to see that worked for you =)
Awesome, works a treat. Saved me some hassle with css. Thanks
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
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!
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
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
hi Glenny, you have 3 options
option 1:
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
the format of your urls links should be (note the forward slash at the end.)
<a href=”/menu” rel=”nofollow”>
option 3: Exact addresses.
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
Hi
This looks excellent – I’ll give it a whirl and let you know how I got on!
Cheers
Glennyboy
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
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.
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
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.
Hi
Would you mind demonstrating that please.
Thanks
Glennyboy