Highlight current link with JavaScript and CSS

It is always a time consuming issue to highlight current link page, specially if you are thinking of going to each page and set the style for the current link. Which is not a bad idea but the problem is, most of the times you would like to put the main navigation of your web pages inside a template. If your navigation is inside a template but you want your current link to be highlighted with a different style you can use some Javascript to do that. There are actually several ways to do that.

You can write a Javascript function to extract the name of you current page, then put that name as an ‘id’ for the body tag of you current page as the page loads.

function returnDocument()
{
var file_name = document.location.href;
return file_name.substring(file_name.lastIndexOf("/")+1, file_name.lastIndexOf("."));

}
window.onload= function()
{
document.getElementsByTagName(’body’)[0].id=returnDocument();

}

all the links in your page will need to have an ‘id’ as well. Then you can just write a css style like this,

body#page1 a#p1,body#page2 a#p2,body#page3 a#p3......
{
specify your style for current link here
}

View the source code of page1.html to see how it is working.

This is a simple way to highlight current link with CSS and JavaScript when you are working keeping the navigation inside a template.

Tags: , , , ,

Leave a Reply

You must be logged in to post a comment.

Custom Search