Highlighting the current menu item

Although there is no JavaScript being used for actually displaying the menu, JavaScript is being used to highlight the menu item that corresponds to the current page.

It's important to be able to do this so the user doesn't get lost. It can be done either server side or client side - I think it is more useful to do it client side.

Client side highlighting allows client side HTML includes

The main reason here to use JavaScript is so the navigation HTML is the same in each page. This means that a client side include can be used to insert the same HTML in each page, so:

Imagine two hundred pages on a site, each with an identical 5kb of navigation. If using server side includes, that navigation HTML is downloaded 200 times - so 1MB of data. If using client side includes, with proper cache headers, the navigation is only downloaded once.

Using frames has the same advantage, but it also has plenty of disadvantages, not least of which is that making a menu in one frame pop-up over text in another is difficult.

How to do client-side includes

There are four ways that I know of, all of which have significant disadvantages:

Using an external entity is, I think, the only good method. It should be supported by any XHTML compatible browser, it allows the browser's normal caching mechanisms to be used, and it doesn't depend on scripting.

The reason I'm not using it for this page is that Mozilla 1.0 doesn't yet support it (see bugs 69799 and 22942).

Update: Kevin Cannon has pointed out that the JavaScript I was using didn't work properly in IE or Opera and provided some fixes. I've updated the code on this page. Thanks!

The menus themselves will still not work properly in IE - and won't until it supports the CSS :hover attribute correctly.

The JavaScript

function getLeaf(url) { return url.substring(url.lastIndexOf("/")+1); } function highlightCurrentMenuItem() { var currentLocation = getLeaf(document.location.href); var menu = document.getElementById("mainmenu"); links = menu.getElementsByTagName("a"); for (i=0; i<links.length; i++) { var currentHref = links[i].getAttribute("href"); var currentLeafName = getLeaf(currentHref); if (currentLeafName==currentLocation) { // Setting class is needed for Mozilla compatibility - className appears to be correct // according to the DOM spec links[i].setAttribute("class", "current"); links[i].setAttribute("className", "current"); // More obvious to use parentNode.parentNode.firstChild, but this // may give a whitespace text node. var menuHeader = links[i].parentNode.parentNode.getElementsByTagName("div").item(0); menuHeader.setAttribute("class", "current"); menuHeader.setAttribute("className", "current"); } } }

Return to index

Return to index