Keydrown
A JavaScript key state handler for web apps
Keydrown is a library for managing the state of the keyboard in a web application or game. It is tiny (about .5Kb), unobtrusive and can be learned in about five minutes.
Why is Keydrown useful?
When you bind a function to the keydown
event, it doesn't fire consistently. The web browser uses the operating system's built-in keyboard delay preferences, and the first brief moment after the initial key press does not invoke the event handler. Here's a demonstration of native behavior:
document.addEventListener('keydown', function (evt) { if (evt.keyCode === 81) { console.log('The "Q" key is being held down...?'); } }); document.addEventListener('keyup', function (evt) { if (evt.keyCode === 81) { console.clear(); } });
Press and hold the "Q" key:
Notice the lag at the beginning of the hold. This sluggishness noticeably impacts the user experience of applications — especially games. A better way to handle the keydown
event is to record when a key is pressed, invoke the handler function for every update, and then stop invoking the handler when an analagous keyup
event is detected. Keydrown makes this really easy:
kd.P.down(function () { console.log('The "P" key is being held down!'); }); kd.P.up(function () { console.clear(); }); // This update loop is the heartbeat of Keydrown kd.run(function () { kd.tick(); });
Press and hold the "P" key:
As you can see, the logging from the code example using Keydrown is much more responsive.
How do I use Keydrown?
Keydrown has no dependencies, so all you need is either one of the following:
All of the Keydrown APIs live under the kd
namespace. Keydrown is tick-based, so you'll need to call kd.tick()
somewhere in your run loop. For your convenience, Keydrown provides kd.run()
for a basic run loop if you don't already have one.
kd.run(function () { kd.tick(); });
To invoke a function when a key is held down, do something like this:
// Function fires when the space bar is held down kd.SPACE.down(function () { // ... });
To invoke a function when a key is released:
// Function fires when the space bar is released kd.SPACE.up(function () { // ... });
...And that's it! You can see what keys Keydrown supports by looking at kd.map.js. You can see the full API documentation here. If you find any bugs, please report them in the Github Issue Tracker. Enjoy!