Javascript Keyboard Interaction

17th August 2014

Sometimes you want to interact with a website by keyboard. Some built-in command like 'tab' jumps from input field to input field.

In more complex scenarios, like browser games, you might want to use the cursers to control objects oder characters on the screen. Or you could use shortcuts like 'ctrl + s' to save things.

Press any key:  
Keycode:  

  ignore key events (e.g. prevent saving page)

Please keep in mind, that there is not a difference for capital an small letters, so:
"s" and "S" have both 83 as key-id
"S" might also have 16+83 ("shift" + "s")

The following examples does not require any thrid-party libraries like jQuery, since they are native Javascript.

Example for single key usage

HTML code, add event handler to body tag

<body onkeydown="keyDown(event)">

Javascript code

function keyDown( key )
{
    if (key.keyCode == 13)
    {
        alert('you pressed enter');

        // stop all standard action
        // e.g. send form
        key.preventDefault();
    }
    else
    {
        //ignore other keys
    }
}

Example for multiple keys

HTML code, add event handler to body tag

<body onkeydown="keyDown(event)" onkeyup="keyUp(event)">

Javascript code

var pressedKeys = [];
function keyDown( key )
{
    // add key to array when pressed
    if ( pressedKeys.indexOf(key.key.toUpperCase()) < 0 )
        pressedKeys.push(key.key.toUpperCase());

    if ( pressedKeys.indexOf(17) >= 0 &&  // keycode for 'ctrl'
         pressedKeys.indexOf(83) >= 0 )   // keycode for 's'
    {
        // stop all standard action
        // e.g. browser saving page
        key.preventDefault();

        // execute you custom action
        alert('you pressed ctrl+s');
    }
    else
    {
        //ignore other keys and key combinations
    }
}
function keyUp( key )
{
    // remove key from array when released
    pressedKeys.splice(pressedKeys.indexOf(key.keyCode),1);
}