Categories
JavaScript Answers

How to capture key press (or keydown) event on DIV element with JavaScript?

Spread the love

To capture key press (or keydown) event on DIV element with JavaScript, we listen for the keyup event.

For instance, we write

document.querySelector("#myDiv").addEventListener("keyup", (e) => {
  console.log(e.key);
});

to select the div with ID myDiv with querySelector.

And then we call addEventListener to listen for the keyup event.

We use a function that logs the key of that’s pressed as the event handler.

e.key is a string with the key’s value.

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 *