keytrack
Track which keyboard keys are currently pressed in the browser.
keytrack is a small npm package that lets you ask whether a key is currently held down in the browser. In JavaScript, you only get keydown and keyup events as they happen, so if you want to know the current state, you have to keep track of it yourself. For games or anything else that checks the keyboard in a loop, keytrack does that for you.
I wrote it for WebTigerPython, where I needed to port the functions isKeyPressed and isKeyCodePressed from TigerJython. You can read more about it in the blog post.
Usage
Install it with npm install keytrack. You turn tracking on with logKeys(true), and then you can query for the keys, e.g. in a game loop:
import { logKeys, isKeyPressed } from "keytrack";
logKeys(true);
function loop() {
if (isKeyPressed("ArrowLeft")) player.x -= 1;
requestAnimationFrame(loop);
}
loop();
isKeyPressed checks the key of the event, e.g. "A" or "ArrowLeft". isKeyCodePressed checks the deprecated numeric keyCode, which keytrack gets from the code with a mapping table for the US keyboard layout. It is mainly there for compatibility with TigerJython; for new code, key might be the better choice. With logKeys(false) you turn tracking off again.
Note that it only works while the browser window is focused, since browsers only send key events to the focused page.
Demo
Click the box, then hold the arrow keys. Hold two at once to move diagonally. Every frame, the loop just asks isKeyPressed(...); there is no key event handling in the demo itself.
This demo was written by Claude.