Submodule 14.3: DOM events
Submodule 14.3: DOM events
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.
Exercise
- Open your editor, create a new file and save it as
exersice14.3.3.html
in the folder "yourNameWEB2JS". - Copy the code below and paste it in the new file.
- Open the file in your browser and arrows on the keyboard.