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.