Sunday, January 11, 2004

JavaScript Hotkeys

I am currently working on an ASP.NET project that required the use of hot keys. Using a JavaScript include on each page I was able to implement the hotkeys. A sample of the code follows:

As you will see by looking through the code, the KeyDown event is captured and various ALT-Key combinations are trapped which redirect the user to different pages of the site. On the page I have the first letter of the hotkey underlined in the menu so that users know which ALT-Key is the hotkey.

In addition to global hotkeys, certain pages of the site also implement their own set of additional hotkeys, and the script checks to see if the page that the user is on has its own set of hotkeys, and if so it calls the function for handling those hot keys (those functions are not shown, but are very similiar to the one shown).

The Code:


function searchHotkeys(e)
{
try
{
// Netscape uses e.which, IE event.keyCode
var eventObj = (e)?e:window.event;
var keyPressed = (e)?e.which:window.event.keyCode;
var altPressed = (e)?(e.altKey):window.event.altKey;

if (altPressed)
{
switch(keyPressed)
{
case 67: // C - Civil
{
if(document.getElementById("SiteMenu_searchCivil"))
{
document.location = "searchCivil.aspx";
}
return;
}
case 82: // R - Criminal.
{
if(document.getElementById("SiteMenu_searchCriminal"))
{
document.location = "searchCriminal.aspx";
}
return;
}
case 77: // M - Marriage.
{
if(document.getElementById("SiteMenu_searchMarriage"))
{
document.location = "searchMarriage.aspx";
}
return;
}
case 80: // P - Property.
{
if(document.getElementById("SiteMenu_searchRecords"))
{
document.location = "searchRecords.aspx";
}
return;
}
}
}

// If we're on a civil suit, check those hot keys.
if (document.location.href.indexOf("Civil") > - 1)
{
return civilHotkeys(altPressed, keyPressed);
}

// If we're on a criminal suit, check those hot keys.
if (document.location.href.indexOf("Criminal") > - 1)
{
return criminalHotKeys(altPressed, keyPressed);
}

// If we're on a marriage license listing, check those hot keys.
if (document.location.href.indexOf("Marriage") > - 1)
{
return marriageHotKeys(altPressed, keyPressed);
}

// Check records hot keys.
if (document.location.href.indexOf("Records") > -1 |
document.location.href.indexOf("Mortgage") > -1 |
document.location.href.indexOf("Chattel") > -1)
{
return recordsHotKeys(altPressed, keyPressed);
}
}
catch(er)
{
// Trap all errors in case of browser javascript
// incompatibilities. We don't want ugly error
// messages popping up everywhere.
//alert(er);
}
}

// Trap key down for hot-key functionality.
if (document.layers)
{
//Needed for Netscape.
document.captureEvents(Events.ONKEYDOWN);
}
document.onkeydown=searchHotkeys;