Kathirvel K

Highlight Current page in menu using Javascript

Posted on: July 13, 2010


<div id=”NavBar”>
<li><a href=”home.html” id=”ctl00_toolbar_hlHome”>Home</a></li>
<li><a href=”services.html” id=”ctl00_toolbar_hlSearch”>Services</a></li>
<li><a href=”about.html” id=”ctl00_toolbar_hlProducts”>About</a></li>
<li><a href=”contact.html” id=”ctl00_toolbar_hlServices”>Contact</a></li>


#NavBar{height: 30px;margin-bottom:2px; border-bottom:2px solid black;}
#NavBar ul{display: inline;padding: 0;margin: 0; width: 960px;}
#NavBar li{list-style-type: none;line-height: 28px;vertical-align: middle;display: block;
text-transform: uppercase;font-size: 12px;float: left;margin-left: 0px;}
#NavBar ul li a{ background: darkred repeat-x;height: 28px;display: block;
text-decoration: none;text-align: center;color: #FFFFFF;margin-right:2px;
padding:0 25px; font-weight:bold; border:1px solid #990200;}
#NavBar ul li a:hover{background: black repeat-x;height: 28px;display: block;
color: #FFFFFF;text-decoration: none;border:1px solid #000000}
#NavBar ul li a.activeMenuItem {background: black; height: 28px;display: block;
color: #FFFFFF;text-decoration: none;border:1px solid #000000}


function extractPageName(hrefString)
var arr = hrefString.split(‘/’);
return  (arr.length<2) ? hrefString : arr[arr.length-2].toLowerCase() + arr[arr.length-1].toLowerCase();
function setActiveMenu(arr, crtPage)
for (var i=0; i<arr.length; i++)
if(extractPageName(arr[i].href) == crtPage)
if (arr[i].parentNode.tagName != “DIV”)
arr[i].className = “activeMenuItem”;
arr[i].parentNode.className = “activeMenuItem”;
function setPage()
hrefString = document.location.href ? document.location.href : document.location;
if (document.getElementById(“NavBar”)!=null)
setActiveMenu(document.getElementById(“NavBar”).getElementsByTagName(“a”), extractPageName(hrefString));


Finally call this JavaScript to all pages:

<script language=”javascript”>setPage()< /script>



2 Responses to "Highlight Current page in menu using Javascript"

Very great post. I just stumbled upon your weblog and wished to mention that I’ve truly loved surfing around your weblog posts. After all I’ll be
subscribing for your rss feed and I am hoping you write again very

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: