I have this code:
else if (e.keyCode == 32){ fired = true;
In a keyDown function (I have added the document.addEventListener code). Now it works just fine, and does exactly what I want it to do. But here's the problem: if you hold down the key, it keeps making fired = true over and over again continuously until it is released. I just want it to set fired = true; once, even if the key is held down.
To cancel keydown with JavaScript, we can call preventDefault in the keydown event handler. For instance, we write: document. onkeydown = (evt) => { const cancelKeypress = /^(13|32|37|38|39|40)$/.
How does a user generate multiple keydown events? Explanation: If the user holds the key down long enough for it to begin repeating, there will be multiple keydown events before the keyup event arrives. Pressing the key for long time results in multiple calls to the function onkeypress.
The keydown event occurs when the key is pressed, followed immediately by the keypress event. Then the keyup event is generated when the key is released.
The keydown event is fired when a key is pressed. Unlike the keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.
Edit: It is now fully supported in every browser. except for Internet Explorer
If browser compatibility is not your main concern*, you could try accessing the .repeat
property of the KeyboardEvent
, as documented here:
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat
By doing something like this in your handler function:
function keyDown (e) { if (e.repeat) { return } // do stuff here }
you could avoid the repeated keystrokes.
*: on the MDN site it states that it works in Firefox, and I have successfully used it in Chrome, so the two major browsers should have no problem with it
var fired = false; element.onkeydown = function() { if(!fired) { fired = true; // do something } };
Then Use onkeyup event
element.onkeyup = function() { fired = false; };
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