View Full Version : highlighting current page hyperlink

03-11-2012, 02:53 PM
Basically all i want to do is highlight the pages hyperlink the user is currently on. So when the home page loads, the home page hyperlink is a different colour to the other hyperlinks, and then when another is page is pressed it is that pages hyperlink that is a different colour to the others

03-11-2012, 03:01 PM
here is how to get the link to the current page ...

for (var as = document.getElementsByTagName('A'), i = as.length; i--; ) {
if (as[i].href == location.href) {/*do whatever*/}

03-11-2012, 05:40 PM
It is not so easy to write a script that can result in your page loading with any links to the current url already colored appropriately.

It is simple to do it after the page loads, but that will change the color of the links after first being displayed with their normal link colors.

function colorReloadLinks(){
var here= location.pathName, next, url,
links= document.getElementsByTagName('a'), L= links.length;
next= links[--L];
if(next.href.indexOf(here)!= -1){
next.style.color= 'green';
next.title+= ' (reload page )';

The change in color (if the link is in the viewable screen area) will draw the eye, probably not what you wanted.

What you can do instead is put a script early in the <head> that sets the style for that page, before the page renders anything visibly.

The next example finds the filename of the loaded page and matches any <a> elements that include the filename in their href attribute.

It is a little involved because links often have pseudo-attributes set for visited, active and hover, and all of them are in the selector.

var css, url=location.pathname,
if(ax) url=url.substring(ax);

css+=', '+css+':visited, '+css+':hover, '+css+':active';


// sample output:

a[href*= "webshop.html"],
a[href*= "webshop.html"]:visited,
a[href*= "webshop.html"]:hover,
a[href*= "webshop.html"]:active{