KeyboardJS
KeyboardJS is a library for use in the browser (node.js compatible). It Allows
developers to easily setup key bindings. Use key combos to setup complex
bindings. KeyboardJS also provides contexts. Contexts are great for single page
applications. They allow you to scope your bindings to various parts of your
application. Out of the box keyboardJS uses a US keyboard locale. If you need
support for a different type of keyboard KeyboardJS provides custom locale
support so you can create with a locale that better matches your needs.
KeyboardJS is available as a NPM module. If you're not using a build system
like webpack, simply add
keyboard.js
or
keyboard.min.js
from the dist folder in this repo to your project via a script tag.
npm install keyboardjs
Note that all key names can be found in ./locales/us.js.
Setting up bindings is easy
keyboardJS.bind('a', (e) => {
console.log('a is pressed');
});
keyboardJS.bind('a + b', (e) => {
console.log('a and b is pressed');
});
keyboardJS.bind('a + b > c', (e) => {
console.log('a and b then c is pressed');
});
keyboardJS.bind(['a + b > c', 'z + y > z'], (e) => {
console.log('a and b then c or z and y then z is pressed');
});
keyboardJS.bind('', (e) => {
console.log('any key was pressed');
});
keyboardJS.bind('alt + shift > a', (e) => {
console.log('alt, shift and a is pressed');
});
keydown vs a keyup
keyboardJS.bind('a', (e) => {
console.log('a is pressed');
}, (e) => {
console.log('a is released');
});
keyboardJS.bind('a', null, (e) => {
console.log('a is released');
});
Prevent keydown repeat
keyboardJS.bind('a', (e) => {
e.preventRepeat();
console.log('a is pressed');
});
Unbind things
keyboardJS.unbind('a', previouslyBoundHandler);
Using contexts
keyboardJS.bind('a', (e) => {});
keyboardJS.bind('b', (e) => {});
keyboardJS.bind('c', (e) => {});
keyboardJS.setContext('index');
keyboardJS.bind('1', (e) => {});
keyboardJS.bind('2', (e) => {});
keyboardJS.bind('3', (e) => {});
keyboardJS.setContext('foo');
keyboardJS.bind('x', (e) => {});
keyboardJS.bind('y', (e) => {});
keyboardJS.bind('z', (e) => {});
myRouter.on('/', (e) => {
keyboardJS.setContext('index');
});
myRouter.on('/foo', (e) => {
keyboardJS.setContext('foo');
});
const contextName = keyboardJS.getContext();
keyboardJS.withContext('bar', () =>{
keyboardJS.bind('7', (e) => {});
keyboardJS.bind('8', (e) => {});
keyboardJS.bind('9', (e) => {});
});
pause, resume, and reset
keyboardJS.pause();
keyboardJS.resume();
keyboardJS.reset();
pressKey, releaseKey, and releaseAllKeys
keyboardJS.pressKey('a');
keyboardJS.pressKey(65);
keyboardJS.releaseKey('a');
keyboardJS.releaseKey(65);
keyboardJS.releaseAllKeys();
watch and stop
keyboardJS.watch();
keyboardJS.watch(myDoc);
keyboardJS.watch(myWin, myDoc);
keyboardJS.watch(myForm);
keyboardJS.watch(myWin, myForm);
keyboardJS.stop();