Kathirvel K

Highlight Current page in menu using Javascript

Posted on: July 13, 2010


HTML:

<div id=”NavBar”>
<ul>
<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>
</ul>
</div>

CSS:

#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}

JavaScript:

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));
}

</script>

Finally call this JavaScript to all pages:

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

Source:http://www.richnetapps.com/automatically_highlight_current_page_in/

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
soon!

Leave a reply to Clifton Cancel reply