Sometimes, we want to check if a key is down with JavaScript.
In this article, we’ll look at how to check if a key is down with JavaScript.
How to check if a key is down with JavaScript?
To check if a key is down with JavaScript, we can check various properties.
For instance, we write
window.onmousemove = (e) => {
if (e.shiftKey) {
//...
}
if (e.altKey) {
//...
}
if (e.ctrlKey) {
//...
}
if (e.metaKey) {
//...
}
};
to get the key pressed in the window.onmousemove method, which runs when we move the mouse.
We check if the shift key is pressed with e.shiftKey.
We check if the altkey is pressed with e.altKey.
We check if the ctrl key is pressed with e.ctrlKey.
And we check if the Windows or command key is pressed with e.metaKey.