Each event handler function receives an event object as the first parameter. This event object holds a lot of details about the current event. In the case of KeyboardEvent, we always have key property present in the object. The key property specifies which key was pressed. There are 3 possible events (keydown, keypress, or keyup) that are triggered when a user interacts with the keyboard.
In the following example, we are going to have one div element and apply some styling to make sure it appears as a circle on the screen. When the user presses arrow keys on his keyboard, we will try to move the div element by changing its position. Please have a look over the code example and steps given below.
HTML & CSS
We have one div element with a class of circle.
We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
We have selected the div element using the document.querySelector() method and stored it circle variable.
We have created the moveBy variable and set its value to 10 since we will change the position of the div element by 10px every time user presses the arrow keys.
We have attached the load event to the window and setting the initial position of the div element at the top left corner. load event will be triggered when the webpage is completely loaded.
We have attached keyup event listener to the window.
Inside the event handler function, we are leveraging the availability of key property in the event object and using a switch statement, to move the object on all 4 sides depending upon the arrow key pressed by the user.
If you notice, we are simply adding or subtracting 10px from the current position of the div element using its style property.