The Key Library

One day when I was trying to create a javascript game, I was baffled when I cam across the problem of not being able to do actions where two keys were required to be pressed down. So I searched the internet looking for any sort of scripts that told me how to do what I needed. I came across a few here and there, but they either weren't what I was looking for or the source was so jumbled that it was impossible to decipher. Then one day as I was looking at a script that showed the key code for the last ley pressed down and the last key released; it hit me! So here is my attempt of recreating the Key object that resides in Flash with javascript. I must say it turned out quite nicely and is exactly what I am looking for.


Download script, examples and documentation:

Specific links:
example 1
example 2
example 3

What does it do?

When you load the script the Key.init() function is called which then creates an array with 256 values set to 'false.' This is for the ASCII key codes. When a key is pressed down, the script sets the specific spot for that code to 'true' in the array, and when you lift the key up, it sets it back to false. When you use the Key.isDown() function it sees if the code passed to the function is set to false in the array. This allows for the recognition of multiple keys at one time.

The Functions

Key.onKeyDown, Key.onKeyUp These are to be used in place of document.onkeydown and document.onkeyup

function exampleFunction() {
	//do something
Key.onKeyDown = exampleFunction;

Key.onKeyDown = function() {
	//do something

//The script will also pass the event object
Key.onKeyDown = function(e) {
	//alert keycode of key pressed

Key.isDown( keycode ) Returns 'true' if a key, specified by its keycode, is pressed down.

Key.onKeyDown = function() {
	if( Key.isDown(65) ) {
		alert("You pressed 'a'!");

Key.addListener( newListener ) Registers an object to recieve onKeyDown and onKeyDown functions. When a key is pressed or released, all objects registered by addListener will have their onKeyDown and onKeyUp methods invoked.

//creates new listener object
var listen = new Object();
listen.onKeyDown = function() {
	//can also have function(e)
	//do something
listen.onKeyUp = function() {
	//do something;

Key.removeListener( listener ) Removes a listener previously registered with addListener syntax:

//if it were to be used with code above


There are some special keywords that KeyLib has to make life easier so you dont have to remember keycodes for keys often used. They are as follows: