I have a javascript function which runs when the 'down' key is pressed. I would like, that if the 'down' key is held down, the function would not run at all.
I thought about timing between keydown and keyup, if the time is less than 1 second then the function would run on keyup. The problem is, if I hold the key down the browser sees it as the key being pressed many times in succession.
Is there a better way to do this?
Thanks
The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup , but as 97 by keypress .
KeyDown occurs when the user presses a key. KeyUp occurs when the user releases a key.
The difference, in case anybody is wondering is that keyup fires when the user releases a key, after the default action of that key has been performed. Keypress fires when an actual character is being inserted in, for instance, a text input. It repeats while the user keeps the key depressed. You can also use Keydown.
KeyDown is raised as soon as the user presses a key on the keyboard, while they're still holding it down. KeyPress is raised for character keys (unlike KeyDown and KeyUp, which are also raised for noncharacter keys) while the key is pressed.
There is a keyboard event property called repeat that returns true if the key is being held down.
document.addEventListener('keydown', (event) => {
if(event.repeat) {
// key is being held down
} else {
// key is being pressed
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With