Hi I need help making my navigation show the active link highlighted on current page. In other words when I click on a link to go to a new page I want to see that link highlighted after the new page is opened. I could handle this with CSS by adding a class to the active link on each page but since there's going to be many pages I would prefer to do this dynamically with JS.

How can I do that with Javascript?... I will appreciate your help, thanks.

Below is the code I'm using feel free to edit as you think convenient.

1 Answer
1

To do this, you'd need to be able to compare some unique element in each link with some other unique element of the page (such as the URL).

Looking at what you have, you might be able to get away with comparing the URLs. You'd have to grab the current' page's location, parse the URL to get the file name (last part of the URL after the last /) and then go through each href of your navigation, parse each one of those, then make a comparison. If there's a match, add a class to that link.

The catch with this is that this isn't the most performant way to handle it. The other issue is if you happen to have two pages on the site with the same file name (which isn't unheard of).

I think uniquely identifying each page with a unique class in the BODY tag is probably the best way to handle it.

So, perhaps your body tag is:

<body class="page-contactus">

And then add a class to your navigation:

<li><a href="contact.html" class="link-contactus">Contact us</a></li>

Then you'd have a block of CSS that will set these on a per-page basis:

Thanks DA but I looking for a method where I don't need to add a class to the body or any element. I need something to work with the URL so if the URL http://... /fileName.html matches the navigation link href="fileName.html" then the link will show as active. Any thoughts on this?
–
rolando.pdlSep 23 '11 at 20:34

my thoughts on that are in my answer...you'd have to compare parts of the page's url to the applicable part of the href attribute. You'd likely need to do some string parsing or regex to get those.
–
DA.Sep 23 '11 at 22:06