Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differentiate between key pressed and key held

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

like image 782
Tom Avatar asked Aug 23 '11 17:08

Tom


People also ask

What is the difference between keypress and Keydown?

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 .

What is difference between Keyup and Keydown?

KeyDown occurs when the user presses a key. KeyUp occurs when the user releases a key.

What is the difference between onKeyUp and onKeyPress?

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.

What is difference between keypress and Keydown event C#?

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.


1 Answers

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
  }
});
like image 132
Brent Stradling Avatar answered Oct 15 '22 09:10

Brent Stradling