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.