We want this scroller to run
really smoothly, so we'll use the type of keyboard handling we've
seen before.
We'll declare an array that keeps track of all the keys that are down at any given time:
var keys = []; // which keys are down
Then we'll add a couple of event listeners that cause a function to be called the moment a key goes up or down:
addEventListener('keydown', MyKeyDownHandler);
addEventListener('keyup', MyKeyUpHandler);
And we'll define those event handling functions to set the appropriate element of the "keys" array to true or false, depending whether the key was going up or down. We'll also override the browser from seeing and acting on the keystroke.
function MyKeyUpHandler(MyEvent) {
keys[MyEvent.keyCode] = false;
MyEvent.preventDefault();
}
function MyKeyDownHandler(MyEvent) {
keys[MyEvent.keyCode] = true;
MyEvent.preventDefault();
}
We've seen this type of code before. It won't cause anything to happen, but it will keep track of the keys without any delays or latency.