I'm trying to create this event to navigate through the website with arrow keys.
The problem that I'm facing is that if someone holds one of the keys, the function (in this case console.log
) will trigger repeatedly which may cause some undesirable behaviour with complex functions.
I want console.log
to be triggered only once for each keydown.
window.addEventListener('keydown', function (e) {
switch (e.key) {
case 'ArrowLeft':
console.log('left');
break;
case 'ArrowRight':
console.log('right');
break;
}
});
I ended up using this:
let allowKey = true;
window.addEventListener('keydown', function (e) {
switch (e.key) {
case 'ArrowLeft':
if (allowKey) {
console.log('Left');
allowKey = false;
}
break;
case 'ArrowRight':
if (allowKey) {
console.log('Right');
allowKey = false;
}
break;
}
});
window.addEventListener('keyup', function(e) {
switch (e.key) {
case 'ArrowLeft':
allowKey = true;
break;
case 'ArrowRight':
allowKey = true;
break;
}
});
Thank you.
you can use the event.repeat to check if the key is already been pressed
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat
window.addEventListener('keydown', (e) => {
if (e.repeat) return;
//your code
switch (e.key) {
case 'ArrowLeft':
console.log('left');
break;
case 'ArrowRight':
console.log('right');
break;
}
});
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