event.key
and modern JS!No number codes anymore. You can use "Enter"
, "ArrowLeft"
, "r"
, or any key name directly, making your code far more readable.
NOTE: The old alternatives (
.keyCode
and.which
) are Deprecated.
document.addEventListener("keypress", function onEvent(event) {
if (event.key === "ArrowLeft") {
// Move Left
}
else if (event.key === "Enter") {
// Open Menu...
}
});