Sometimes, we want to capture key press or keydown event on a div element with JavaScript.
In this article, we’ll look at how to capture key press or keydown event on a div element with JavaScript.
How to capture key press or keydown event on a div element with JavaScript?
To capture key press or keydown event on a div element with JavaScript, we listen to the keyup event.
For instance, we write
document.querySelector("#myDiv").addEventListener("keyup", (e) => {
console.log(e.key);
});
to select the div with document.querySelector("#myDiv").
Then we call addEventListener on it with 'keyup' and a function that runs when we release the key that’s pressed.
In it, we get the key released with e.key.
Conclusion
To capture key press or keydown event on a div element with JavaScript, we listen to the keyup event.