How to capture key press or key down event on DIV element with JavaScript?

Spread the love

Sometimes, we want to capture key press or keydown event on DIV element with JavaScript.

In this article, we’ll look at how to capture key press or keydown event on DIV element with JavaScript.

How to capture key press or key down event on DIV element with JavaScript?

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

For instance, we write

<div id="myDiv" tabindex="0">Press me and start typing</div>

to add a div.

Then we write

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

to select the div with querySelector.

And we call addEventListener on it to listen to the keyup event.

In the event listener, we get the key pressed with e.key.

Conclusion

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

Leave a Reply

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