Using the keyboard arrow keys

Today’s post is a rather short and simple one. In most client-based games today, you can move using your keyboard. Browser-based games, however, are usually controlled using the mouse. But though using the arrow or WASD keys to interact with web pages is not too common, it can still be quite useful.

In a web page, any key you press triggers an event, so using the keyboard to control a browser-based game is as simple as listening for and catching these events. Listening for keyboard events is fairly easy if you’re using JavaScript, and with jQuery it’s even easier. Before we get properly started, I’d like to introduce a very simple and useful jQuery plugin called HotKeys, which can help you attach to events in a simple manner. You can find it here, and binding with it is a simple matter of:

$(document).bind('keydown', 'Ctrl+c', fn);

Sometimes, however, you want to do things yourself and not use a plugin. As I said, that is simple as well. You probably already know how to bind an input box to the Enter key:

$("#my_input_field").keydown(function(event){
    If ( event.keyCode == 13 ){
        // Do whatever – enter key was pressed
}
});

Binding to other keys is pretty much the same. All you need to know is the code for your wanted key. For example, if you want to support the arrow keys you can use something like this:

$(document).keydown(function(event){
    switch (event.keyCode) {
            case 37:
                moveLeft();
                break
            case 38:
                moveUp();
                break;
            case 39:
                moveRight();
                break;
            case 40:
                moveDown();
                break;
        }});

You can also add support for the space key if you want; its code is 32.

’till next time,
Adi Gabai

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories