JavaScript keyboard input detection and response

Page content

Any game needs to be able to respond to input from the user, and ours is no exception. So lets look at how we can respond to the keys being pressed on the keyboard in order to move a character around on the screen.


There are two events that we are interested in when responding to keyboard input: onkeydown and onkeyup. As the name suggests the onkeydown event is triggered when a key is pressed, and the onkeyup event is triggered when a key is released. Actually, the onkeydown event is triggered repeatedly if you hold a key down, in much the same way as a character would be repeatedly added to a Word document if you held the key down. This doesn’t make any difference to our game, but is worth noting. [code]

We create two new functions in the GameObjectManager to be called when these events are triggered: keyDown and keyUp. These two functions loop through the gameObjects collection and call the keyDown and keyUp functions on the game objects (if the functions have been defined). [code]


The Player class (an Application class) has been created to respond to the keyboard events by defining the keyUp and keyDown functions that the GameObjectManager attempts to call above. The Player class extends the AnimatedGameObject class, because it will move an animated character around on the screen.

The Player class has four Boolean properties, one for each direction it can move (up, down, left and right). [code]

In the keyDown function these values are set to true if the appropriate arrow key has been pressed, and the keyUp function will set these values to false. You’ll notice that the arrow keys are defined by the keyCode property on the event object passed to the function. If you need to know what keyCode corresponds to which keyboard key, you can visit this page, which contains some JavaScript demos that show you the keycode for any key press event. [code]

In the update function the Player class will move itself across the screen, stopping at the edges. [code]

Check out the demo here, download the source code here, and browse the code documentation here.

Read more in the Game Development with JavaScript and the Canvas element series.