Categories
JavaScript Answers

How to take keyboard input in JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *