Sometimes, we want to detect keypresses in JavaScript.
In this article, we’ll look at how to detect keypresses in JavaScript.
How to detect keypresses in JavaScript?
To detect keypresses in JavaScript, we can listen to the keypress
event.
For instance, we write
document.onkeypress = (e) => {
console.log(e.keyCode);
};
to set document.onkeypress
to a function that runs when we press a key on the page.
In the function, we get the key code of the key that’s pressed with e.keyCode
.
Conclusion
To detect keypresses in JavaScript, we can listen to the keypress
event.