About This Product
Metachecker.net | TrafficChecker.net | RankChecker.net
| Over 5000 Free Fonts | Tutorials | Javascript Forum | Other Javascript Resources | Cheat Sheet


This script extends an element with a few simple methods to handle keyboard inputs. A good example where this might be useful is in a webapp where one would like to have keyboard shortcuts defined.

Extending HTML elements

As you probably knows by IE4+ supports expando properties on HTML elements. This means that IE remembers all properties on an HTML element although it doesn't know what to do with them. For example one might add an attribute called overSrc to an image element that can then be used in a custom script. A much lesser known feature is the expando methods. With this you can add methods to any HTML element. I'll show you a small (stupid) example.

document.all.anElement.setBackgroundColor = function (color) {
   this.style.backgroundColor = color;
}

Now one can call document.all.anElement.setBackgroundColor("white") to change the background color. Although this can be done in many different (and easier ways) this method allows a higher level of abstraction. Notice that this is the name of the actual element.

Keyboard Extensions

The first thing that is done is to add an expando property that contains an associative array that keeps track of the added keyboard shortcuts.

element._keyObject = new Array();
element._keyObject["keydown"] = new Array();
element._keyObject["keyup"] = new Array();
element._keyObject["keypress"] = new Array();

Then there are some expando methods added to add and remove keyboard shortcuts. These are kept in the right array according to the event type they are assosciated to.

element.addKeyDown = function (keyCode, action) {
   element._keyObject["keydown"][keyCode] = action;
}

element.removeKeyDown = function (keyCode) {
   element._keyObject["keydown"][keyCode] = null;
}

Hooking up the events

For this we first need a function for handling the event. This is also pretty straight forward and it checks the type of event and what key was pressed. With this info it looks if there is any action assosciated to this event and keycode and if there is it just calls that action. After this is done it justs assigns the function the event handlers of the element.

function handleEvent() {
   var type = window.event.type;
   var code = window.event.keyCode;

   if (element._keyObject[type][code] != null)
      element._keyObject[type][code]();
}

element.onkeypress = handleEvent;
element.onkeydown = handleEvent;
element.onkeyup = handleEvent;

Usage

First you need to include the javascript file.

<script type="text/javascript" src="keyhandler.js"></script>

Then you need to add all the expando properties and methods but to make it easy for you I've created a function that does all this for you. This should not be called before the element is available.

addKeyHandler(document.body);

Notice that not all elements support keyboard events. Once this is done you can start adding your keyboard shortcuts. I'll show you how this is done in the demo section below.

Demo

Basic

Adding a single keyboard shortcut is easy. To find out the keyCode value use this.

document.body.addKeyPress(32, function(){alert("You pressed Space");});

This will result in an alert when space is pressed. Keyboard associations can be changed during run time. Below are two buttons, one that adds a keydown handler for the a key and on that removes the same.

<button onclick="document.body.addKeyDown(65, function(){alert('a pressed');})">
Add handler for <b>a</b></button>
<button onclick="document.body.removeKeyDown(65)">
Remove handler for <b>a</b></button>

The enter key has been hooked up to increase a counter.

var counter = 0;
function increaseCounter() {
   window.status = "counter = " + counter++;
}

document.body.addKeyPress(13, increaseCounter);document.body.addKeyPress
(13, increaseCounter);

Using multiple keys

I haven't built in any special handling of multiple keys but this can be achieved a few simple ways. The window.event object has three properties that indicates whether the alt, ctrl or the shift key was pressed and these are called altKey, ctrlKey and shiftKey. Below is a handler that gives an alert if the user presses CTRL + C.

document.body.addKeyDown(67, function() {if (window.event.ctrlKey) alert
("CTRL + C");});

To catch two keys where none of them are alt, ctrl or shift you need some more handling. The idea here is to have a boolean variable that indicates whether a key is down and then if both are true do something.

var w, q;
document.body.addKeyDown(81, function() {q = true; if (q && w)
window.status = "q and w is pressed";});
document.body.addKeyUp(81, function() {q = false;
window.status = "";});

document.body.addKeyDown(87, function() {w = true; if (q && w)
window.status = "q and w is pressed";});
document.body.addKeyUp(87, function() {w = false;
window.status = "";});

KeyCode tool