This subject recently came up
here.
Many websites, in their main navigation, have an indicator in the navigation of which page you are on, anything from the lightening of the link to give the appearance of a tab, to a separate link color, or boldness, etc. I wanted to show everyone a simple way to do this with JavaScript, that will work even if your pages have subsections of dynamic content on them (ex:
http://example.com/news?article=21).
Let's start with an HTML structure. For our purposes, this will be a simple menu contained by an unordered-list:
HTML Code:
<ul id="nav">
<li><a href="/">Home</a></li>
<li><a href="/about.html">About</a></li>
<li><a href="/contact.html">Contact</a></li>
</ul>
Notice that the <ul> has an id of "nav" on it. This is important as we'll be using it to target the anchors within it. Now, let's assume that all of these pages are linked to a JavaScript file called "navigation.js":
Let's link to this file at the very bottom of the page, right before the closing </body> tag. We could also place it inside of an onload event, but that would mean waiting for the images to load, which would not be optimal in this case:
HTML Code:
<script type="text/javascript" src="navigation.js"></script>
</body>
navigation.js:
Code:
var menu = document.getElementById("nav").getElementsByTagName("a");
//creates an array out of each "a" element
for(var i=0; i<menu.length; i++) {
if(menu[i].href == "http://"+window.location.hostname+window.location.pathname) {
// comparing each href vs this allows for query and hash variables
menu[i].className="active";
// add class of "active" if there is a match
}
}
Now, we make a style for the class="active" which is being added to the link if its href matches our special window location. In this case, we'll simply make the color of the link red:
CSS
Code:
a.active {
color: red ;
}
That's it, simple as eating cake. The nice thing about this method, as opposed to other ways of doing this, is that it is easy to add many more menu items to the navigation, without ever needing to add more logic to your script, or needing to manually insert anything else to make the navigation behave. You simply link to the same script.