This package has been deprecated

Author message:

This package has been renamed to key-state. Consider using it instead.

keyboard-state

0.1.0 • Public • Published

keyboard-state

Simple keyboard state tracker

function loop() {
  if (keys.ArrowLeft) {
    move(hero, 'left')
  }
  if (keys.ArrowRight) {
    move(hero, 'right')
  }
  requestAnimationFrame(loop)
}

install

npm install keyboard-state

usage

To begin listening for events, call the function exported by this module (listen) with the element that you'd like to scope down key events to (usually window).

const listen = require('keyboard-state')

var keys = listen(window)

listen returns the keyboard state (keys) in the form of an object which maps browser-defined key names as defined by event.key (Enter, ArrowUp, p...) to the amount of frames the key in question has been held down.

The keys map is populated and updated automatically as key events are received. If a key hasn't been pressed since the map was created, it will evaluate to undefined.

Since a key that isn't being pressed gets mapped to either 0 or undefined, you can check if a key is being pressed by determining if its value is truthy.

if (keys.Enter) {
  // The enter key is being pressed. Wow
}

If you'd prefer to use names other than the browser-defined key names, consider using object-rename to switch them out for something else.

license

MIT © Brandon Semilla

Package Sidebar

Install

npm i keyboard-state

Weekly Downloads

1

Version

0.1.0

License

MIT

Last publish

Collaborators

  • semibran