Some Examples

We'll cover the following...

Now that you’ve seen the horribly boring basics of how to work with Keyboard events, let’s look at some examples that clarify (or potentially confuse!) everything you’ve seen so far.

Checking that a Particular Key Was Pressed

The following example shows how to use the keyCode property to check if a particular key was pressed:

Press + to interact
window.addEventListener("keydown", checkKeyPressed, false);
function checkKeyPressed(e) {
if (e.keyCode == "65") {
alert("The 'a' key is pressed.");
}
}

The particular key I check is the a key. Internally, this key is mapped to the keyCode value of 65. You can find a handy list of all key and character codes at the following link. Please do not memorize every single code from that ...