I don't know why this appears to be so difficult to figure out. I want to be able to execute code when a key is pressed and held but only once. Instead when I use onkeypress or onkeydown the function that I bound gets executed repeatedly which is not what I want. How can I have the handler be executed just once when the key is held down?
Note: I don't want to embed logic into the function that will limit its execution, I want it not to be firing the event more than once no matter how long I hold the key.
Here is the demo and the code
HTML
<div id="counter">0</div>
JS
var counter = 0,
div = document.getElementById('counter');
document.body.onkeypress = function(){
div.innerHTML = counter++;
}
Notice how when you press and hold any key the counter keeps going, I want it to count just once no matter how long I hold the key, and keep in mind the notice from above.
Sorry forgot to mention removing the listener is not acceptable, I need to increase the counter by 1 every time a key is pressed but no matter how long it's held.
You do have to use logic to avoid repetitive events on a key being pressed, because there's no specific and compatible event for key being just pressed.
More specifically, the easiest solution is to store a boolean, setting it true on key up, false on key down (after having done your action), and ignoring the key down event while it's false:
(function(){
var shouldHandleKeyDown = true;
document.onkeydown = function(){
if (!shouldHandleKeyDown) return;
shouldHandleKeyDown = false;
// HANDLE KEY DOWN HERE
}
document.onkeyup = function(){
shouldHandleKeyDown = true;
}
})();
Demonstration
EDIT for 2019
Now that IE is dead, you can also use the event.repeat property, which is true when the event is a repetition.
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