Friday, July 14, 2006

Auto Highlighting Navigation

I found this page "Automatically highlight current page in menu via JavaScript" within the Media Division Developers' Blog.

It's pretty clever and has saved me a lot of development time already, but I found a bug in it that can prompt error messages.

The script relies on the tokenising of the URL in the browser window, comparing the final tokens with linked pages within the navigation area of a page. This works really nicely unless the URL is incomplete, for example http://www.mysite.com/folder/. This has no file reference such as "index.htm" to work with and rather than handling this, it stumbles over the JavaScript version of a null pointer error looking for an item in an array with index -1.

The fix I'm using is a conditional statement, which makes sure that everything has been setup as expected, allowing it to bow out gracefully, (i.e. not highlight anything) rather than throwing up errors. Here's the effected function:


function extractPageName(hrefString)
{
var arr = hrefString.split('.');
if(arr.length >= 2) {
arr = arr[arr.length-2].split('/');
return arr[arr.length-1].toLowerCase();
} else {
return "x";
}
}

No comments: