Keyboard Events

In addition to click and mouse events, we also have the keyboard events which can be used to perform actions when the user presses a key. On the Working With the Keyboard you can find more information about how to use them.

In order to be able to perform an action when a particular key is pressed, we need a way to determine which key has been pressed.

There are two ways to do that, the first is by defining it on our code using its Unicode value. On this table you can find the values for each key of the keyboard. Using this value we can use :

event.which == x || event.keyCode == x  on the code to define the key which will trigger the event.

The second way to do that is by using KeyboardEvent.key Values . Using that way, we will write key="ArrowRight" instead of keyCode==39 to trigger an event when the Right Arrow has been pressed.

Although the second way is more straightforward, there can be implications when using non-standard keyboards.

Here we will use the first way to see an example where we add 1 on a variable when the right arrow is pressed and subtract 1 when the left arrow is pressed.

Code:

Exercise

    1. Open your editor, create a new file and save it as exersice14.3.3.html in the folder "yourNameWEB2JS".
    2. Copy the code below and paste it in the new file.
    3. Open the file in your browser and arrows on the keyboard.