HTML and CSS Reference
In-Depth Information
}
}
window.addEventListener('keydown', onKeyboardEvent, false);
};
</script>
</body>
</html>
Often, you won't know the exact numeric value of the key you want to capture. To make finding
this information easier, we've created a file
keycode.js
to use as a reference cheat-sheet or to
include in your document, so you can lookup a key by name instead of number—this makes your
code much easier to understand. This script creates a global object
keycode
that contains the
property names of most keyboard keys and maps them to their associated
keyCode
value. You
Let's rewrite the previous example using key names instead of key codes. Place the file
keycode.js
in the same directory as the example and include it in the document
08-key-
names.html
:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Key Names</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<script src="keycode.js"></script>
<script>
window.onload = function () {
function onKeyboardEvent (event) {
switch (event.keyCode) {
case keycode.UP:
console.log("up!");
break;
case keycode.DOWN:
console.log("down!");
break;
case keycode.LEFT:
console.log("left!");
break;
case keycode.RIGHT:
console.log("right!");
break;
default:
console.log(event.keyCode);
}
}