Handling keyboard events in JavaScript

Published 23. Sep 2010, 00:01
Files KeyInputHandler.js

Handling keyboard events is a cumbersome task. When the major browsers decided to implement this there were no standards to follow, so key definitions vary from browser to browser.

First of all we need to bind a callback function to an event that is triggered by a keyboard action. We got the following events: onkeypress, onkeydown and onkeyup. The only event I've found to be reliable is onkeydown, so I'm going to stick with that in this article.

Here's how you may implement a very basic key event callback function.

function handleKeyEvent: function(ev)
{
	ev = ev || window.event;
		if (ev.KeyCode == 190)
		{
			alert('You pressed the dot character. Or did you?');
		}
}

document.onkeydown = handleKeyEvent;

Everything looks swell and it's adequate for a few keys. For browser compatibility you have to do slightly more as the keycodes varies irregularily. For instance, in the previous example the keycode for the dot (.) sign is actually 46 in Opera. So you might do something like this:

function handleKeyEvent: function(ev)
{
	ev = ev || window.event;
	var browser = navigator.appName.toLowerCase();
		if ((browser == 'opera' && ev.KeyCode == 46) || (browser != 'opera' && ev.KeyCode == 190))
		{
			alert('You pressed the dot character. I\'m fairly certain of that now.');
		}
}

Yes, it's not pretty, but it works. The catch is that every new key event has to be explicitly entered into the callback function. This makes it impractical in a situation where you want a more dynamic solution. For example if you want to add certain key events only to certain page(s), this basic approach is far from ideal. To deal with this issue I made a class to handle the key events for me.

Let me introduce the KeyInputHandler class. It's not perfect, but it's easily extendable and thus can be adequate for most needs. Here's an example of me binding the H key to an anonymous callback using the KeyInputHandler.

KeyInputHandler.registerKey(KeyInputHandler.KEY_H, function()
{
	alert('You pressed H!');
});

document.onkeydown = KeyInputHandler.checkKey;

Here the KeyInputHandler.checkKey function does all the work for us. We never need to change its content. We can register keys on demand.

Notice that the first argument was a class constant and not explictly a letter or digit (not a true constant, but hey it's written all in uppercase!), this is kind of important. If you extend the class with a new key you should always use a constant instead of a value. The second argument is the callback function that is called whenever the key is pressed. Because of my lack of creativity I'm only alerting a string, but here you could for example redirect the user to a different page or something else fancy.

Here's some articles I recommend for further reading. These authors have done extensive research on keys and browser compatibility.
http://unixpapa.com/js/key.html
http://www.quirksmode.org/js/keys.html

Files

View Source: KeyInputHandler.js
Download: KeyInputHandler.js

Back to the top