HTML and CSS Reference
In-Depth Information
window.addEventListener('keydown', onKeyboardEvent, false);
window.addEventListener('keyup', onKeyboardEvent, false);
};
</script>
</body>
</html>
Key codes
More often than not, within the event handler function, you'll want to know which key has been pressed.
Earlier, when introducing events, you saw that an event handler gets passed an event object, which
contains data about the event that just occurred. In a keyboard event, you can use the
keyCode
property
to determine what key was involved with the event.
The
keyCode
property contains a numeric value that represents the physical key that was pressed. If the
user pressed the “a” key, the
keyCode
would contain the number 65, regardless of what other keys were
pressed. If the user pressed the Shift key first and then “a,” you would get two keyboard events: one for
Shift
(keyCode
16) and one for “a” (
keyCode
65).
In the next example, we're testing the
keyCode
against a set of known values, the numbers of the
directional arrow keys: 37, 38, 39, and 40. If it matches any of these numbers, we print a message to the
console displaying the direction that has been pressed. Otherwise, we just print out the
keyCode
value of
the unknown key. Here is the document
07-key-codes.html
:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Key Codes</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<script>
window.onload = function () {
function onKeyboardEvent (event) {
switch (event.keyCode) {
case 38:
console.log("up!");
break;
case 40:
console.log("down!");
break;
case 37:
console.log("left!");
break;
case 39:
console.log("right!");
break;
default:
console.log(event.keyCode);