Sometimes, we want to capture key press without placing an input element on the page with JavaScript.
In this article, we’ll look at how to capture key press without placing an input element on the page with JavaScript.
How to capture key press without placing an input element on the page with JavaScript?
To capture key press without placing an input element on the page with JavaScript, we can listen for keyboard events in the document
.
For instance, we write
document.onkeydown = (evt) => {
if (evt.ctrlKey && evt.keyCode === 90) {
console.log("Ctrl-Z");
}
};
to set the document.onkeydown
property to a function that checks if ctrl+z is pressed.
We check for ctrl key press with evt.ctrlKey
and we check for the z key press by checking if keyCode
is 90.
Conclusion
To capture key press without placing an input element on the page with JavaScript, we can listen for keyboard events in the document
.