funkey

1.0.3 • Public • Published

funkey CircleCI npm Coverage Status

Funkey is a self-currying keyboard event handler. You provide the keyboard event, funkey provides the fun. http://bukk.it/hahano.png

Download

Direct: Build (minified)

Using npm:

$ npm i --save funkey

Basic Usage

document.addEventListener('keydown', (event) => {
  funkey(event, 'super+enter', () => { 
    console.log('super enter pressed!');
  });
})

Arguments

  • keyboardEvent - A keyboard event to handle.
  • keyName - The keyboard key combination to match.
  • callback - A callback to invoke with event if keyName matches event.

The KeyName

The keyName is made up of the modifiers and the key itself. The available modifiers are ctrl, alt, shift and super. The available key names are a single character, or a named key, which may be one of:

f1-12, tab, backspace, enter, shift, pause, capslock, escape, space, pageup, pagedown, end, home, left, up, right, down, insert, delete, select, multiply, add, subtract, decimal, divide, numlock, scrolllock, numpad0-9

Currying

Funkey is self-currying and the keyboard event argument can be given in any position when invoking funkey. This makes funkey pretty flexible. Here are some examples:

document.addEventListener('keydown', (event) => {
  var onKeypress = funkey(event);
  onKeypress('super+enter', (e) => { /* take action! */ });
  onKeypress('super+esc', (e) => { /* escape! */ });
  onKeypress('shift+ctrl+super+s', (e) => { /* ¯\_(ツ)_/¯ */ });
})
var onEnterDoStuff = funkey('enter', () => { /* do stuff */ });
var onEscapeDoOtherStuff = funkey('escape', () => { /* do other stuff */ });
 
document.addEventListener('keydown', (event) => {
  onEnterDoStuff(event);
  onEscapeDoOtherStuff(event);
});
var logMessage = () => console.log('hello world!');
var onShiftDown = funkey('shift+down');
document.addEventListener('keydown', onShiftDown(logMessage));

The callback context is also correctly maintained:

const controller = {
  doSomething: function() {},
  onKey: funkey('shift+/', function() {
    this.doSomething();
  })
};
 
document.addEventListener('keydown', controller.onKey.bind(controller));

Roadmap

  • Improved docs
  • Impliment newer KeyboardEvent.key property parsing.

References

Inspiration and sources.

Contributing

Don't be shy! Submit issues (or better yet PRs) if you see anything that could be better. If you're submitting code that contains patches or features please try to include unit tests. Thanks!

Author

Piet van Zoen hi@pietvanzoen.com

License

MIT : http://opensource.org/licenses/MIT

Dependents (0)

Package Sidebar

Install

npm i funkey

Weekly Downloads

3

Version

1.0.3

License

MIT

Last publish

Collaborators

  • pietvanzoen