I want to have a onkeydown
event fire a function only once. for that function to fire again, the user has to release the key and press/hold again.
I know its fairly simple but I'm new at JS. Also I prefer to avoid using jQuery or other libs.
One more thing, this should work for both ie and firefox.
The onkeydown event occurs when the user is pressing a key (on the keyboard).
The onkeydown attribute fires when the user is pressing a key (on the keyboard).
The onKeyDown event is triggered when the user presses a key. The onKeyUp event is triggered when the user releases a key.
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)$/.
You could set a flag:
var fired = false;
element.onkeydown = function() {
if(!fired) {
fired = true;
// do something
}
};
element.onkeyup = function() {
fired = false;
};
Or unbind and rebind the event handler (might be better):
function keyHandler() {
this.onkeydown = null;
// do something
}
element.onkeydown = keyHandler;
element.onkeyup = function() {
this.onkeydown = keyHandler;
};
More information about "traditional" event handling.
You might also want to use addEventListener
and attachEvent
to bind the event handlers. For more information about that, have a look at quirksmode.org - Advanced event registration models.
I'm surprised it's not mentioned, there's also event.repeat
:
document.addEventListener('keydown', (e) => {
if (!e.repeat)
console.log(e.key);
});
This will only fire once per each keypress, since event.repeat
turns true
after holding the key down.
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key#keyboardevent_sequence
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