2 ways of Javascript menu or navigation highlighting
The following two ways are the way I do client side javascript menu highlighting. These work well if you have a site navigation or menu and you want to dynamically highlight the page that you are currently on. I use Method 1 when I have only a few items in the nav, as the JS for it is super easy, or I need to have relative URLs in my menu. Method 2 is better when there are a lot of items, as it relies only on the href and url and doesn't need any extra stuff in the HTML. It does need absolute URLs in the menu href's though in order to match correctly with the url.
Method 1 - This method relies on the fact that you will put id's on each of the a elements with the value of the file name of that file. The HTML shows what I mean. The JS then just looks at the file name of the URL and makes that ID active. Super easy. There is also an "else" statement at the end of the JS so if the file name is blank because you are on "http://yourdomain.com/" it goes ahead and highlights the index menu item.
<div id="topMenu"> <ul> <li><a id="index" href="">Blog</a></li> <li><a id="about" href="about.html">About</a></li> <li><a id="race_car" href="race_car.html">Race Car</a></li> <li><a id="contact" href="contact.html">Contact</a></li> </ul> </div> <script type="text/javascript" language="javascript"> var fileName=location.href.toLowerCase().substring( location.href.lastIndexOf("/")+1 ).split('.')[0]; if (document.getElementById(fileName)) {document.getElementById(fileName).className = "active";} else {if (fileName == '') {document.getElementById('index').className = "active";}} </script>
Method 2 - This method does not need any id's in the a elements. What it does it look through the href statements in your menu and compares them to the URL. This method works better for larger menus.
<div id="topMenu"> <ul> <li><a href="http://www.tomhoppe.com/test/index.html">Blog</a></li> <li><a href="http://www.tomhoppe.com/test/about.html">About</a></li> <li><a href="http://www.tomhoppe.com/test/race_car.html">Race Car</a></li> <li><a href="http://www.tomhoppe.com/test/contact.html">Contact</a></li> </ul> </div> <script type="text/javascript" language="javascript"> var theUrl = location.href.toLowerCase(); var navLinks = document.getElementById('topMenu').getElementsByTagName('a'); if (theUrl == 'http://www.tomhoppe.com/test/') { navLinks[0].className = 'active'; } else { for (var i=0; i<navLinks.length; i++) { var NavLinkUrl = navLinks[i].getAttribute('href').toLowerCase(); if (NavLinkUrl == theUrl) {navLinks[i].className = 'active';} } } </script>
Labels: All, CSS, Javascript