Highlighting the Current Navigation Tab with Javascript and PHP

November 18th, 2008

One of our projects required highlighting of the current navigation tab. So naturally, I googled and here’s what I found:

  • http://www.alistapart.com/articles/keepingcurrent
  • http://www.hicksdesign.co.uk/journal/highlighting-current-page-with-css
  • http://www.websiteoptimization.com/speed/tweak/current/

However, none of them was the solution to what we exactly needed because of our file structure. We had a unique sidebar navigation include (nav.inc.php) for every subdirectory.

The ALA solution was ugly, they inserted php snippets in every <li> entry. Hicksdesign’s solution was ok, but it required coding in a unique ID on every individual page, which was not a good idea for us.

So we came up with our own solution.

Here’s what we did:

  1. Get the Page’s name. In this case, our URL was structured in this way, http://website.com/category1/section1/page-name
  2. Set IDs to each of the sidebar navigation links, to match the page names.
  3. Invoke javascript to set class=”selected” to the navigation link where the current page is on.

Here’s the Javascript code that was used:

<script language="javascript">
function set_current_nav()
{
	document.getElementById('<?=$current_page?>').setAttribute('class','selected');
}
set_current_nav();
</script>