Keyboard events as well as mouse events. This event can listen on following actions:
- keydown – fired when a keyboard key is pressed and lasts as long as the key is pressed
- keyup – occurs when a keyboard key is released
- keypress – fired when a keyboard key is pressed, but after the keydown event and before the keyup event. Please note that this event is generated only for those keys that generate output in the form of characters, for example, when printing characters. Pressing other keys, for example, Alt, are not taken into account.
A KeyboardEvent object is defined to work with keyboard events. This object adds a series keyboard-specific properties:
- altKey – returns true if the Alt key was pressed while the event was being generated
- key – returns the character of the pressed key, for example, when pressing the “T” key, this property will contain “T“. And if the “Я” key is pressed, then this property will contain “Z”
- code – returns a string representation of the pressed key of the physical QWERTY keyboard, for example, when pressing the key “T” this property will contain “KeyT“, and when pressing the key “;” (semicolon), then the property will return “Semicolon“.
If you switch the layout, the character from the QWERTY keyboard will still be transmitted. - ctrlKey – returns true if the Ctrl key was pressed while the event was being generated
- metaKey – returns true if the keyboard meta key was pressed during the event generation
- shiftKey – returns true if the Shift key was pressed while the event was being generated
For example, we can use the keyboard keys to move an element on a web page:
<head> <meta charset="utf-8" /> <title>Test</title> </head> <body> <div id="blueRect"></div> <script> function moveRect(e){ var blueRect = document.getElementById("blueRect"); //get style for blueRect var cs = window.getComputedStyle(blueRect); var left = parseInt(cs.marginLeft); var top = parseInt(cs.marginTop); switch (e.key) { case "ArrowLeft": //if the left key is pressed if (left > 0) blueRect.style.marginLeft = left - 10 + "px"; break; case "ArrowTop": //if the up key is pressed if (top > 0) blueRect.style.marginTop = top - 10 + "px"; break; case "ArrowRight": //if right key is pressed if (left < document.documentElement.clientWidth - 100) blueRect.style.marginLeft = left + 10 + "px"; break; case "ArrowDown": //if down key is pressed if (top < document.documentElement.clientHeight - 100) blueRect.style.marginTop = top + 10 + "px"; break; } } addEventListener("keydown", moveRect); </script> </body>
In this case, the keydown event is handled. In the moveRect handler using the window.getComputedStyle() method.
Using the e.key property, we get the pressed key. The list of keyboard key codes can be viewed on the page – Key_Values