Sometimes, we want to take keyboard input in JavaScript.
In this article, we’ll look at how to take keyboard input in JavaScript.
How to take keyboard input in JavaScript?
To take keyboard input in JavaScript, we listen to the keydown event.
For instance, we write
document.addEventListener("keydown", (event) => {
if (event.keyCode === 37) {
console.log("Left was pressed");
} else if (event.keyCode === 39) {
console.log("Right was pressed");
}
});
to listen for the keydown event on the document with addEventListener.
We listen for key presses on the whole page.
In it, we check the keyCode value.
If it’s 37, then the left arrow is pressed.
And if it’s 38, then the right arrow is pressed.
Conclusion
To take keyboard input in JavaScript, we listen to the keydown event.