If the user holds down the key, multiple keydown events are fired. For usability reasons I need to use keydown, not keyup, but I want to avoid this situation. My relevant code is the following:
$(document).keydown(function(e) { var key = 0; if (e == null) { key = event.keyCode;} else { key = e.which;} switch(key) { case config.keys.left: goLeft(); break; case config.keys.up: goUp(); break; case config.keys.right: goRight(); break; case config.keys.down: goDown(); break; case config.keys.action: select(); break; } });
So when the user holds down the down key, for example, goDown() is fired multiple times. I would like it to fire just once even if the user holds the key 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 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.
The keydown event is triggered first when user presses a key. The keyup event is triggered last when user releases a key. In between, the keypress event is triggered.
Use event.repeat
to detect whether or not the event is repeating. You could then wait for "keyup" before allowing the handler to execute a second time.
var allowed = true; $(document).keydown(function(event) { if (event.repeat != undefined) { allowed = !event.repeat; } if (!allowed) return; allowed = false; //... }); $(document).keyup(function(e) { allowed = true; }); $(document).focus(function(e) { allowed = true; });
Another simple adjustment to the accepted answer to allow for the multiple keys scenario:
var keyAllowed = {}; $(document).keydown(function(e) { if (keyAllowed [e.which] === false) return; keyAllowed [e.which] = false; // code to be executed goes here }); $(document).keyup(function(e) { keyAllowed [e.which] = true; }); $(document).focus(function(e) { keyAllowed = {}; });
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