README
whatkey
A translator for javascript keyboard events to and from consistent and familiar character and key representations.
Take your keydown
, keypress
, and keyup
events and reliably translate them into keyboard keys and characters.
Example
myCanvas.addEventListener('keydown', (event) => {
const key = whatkey(event).key;
if (key === 'w') {
goUp();
} else if(key === '\n') {
confirm();
} else if (key === 'shift') {
if (event.location === 1) { // left shift
shiftDown();
} else { // right shift
shiftUp();
}
} else if (key === '\b') {
event.preventDefault(); // prevent changing pages
} else {
const char = whatkey(event).char;
if (char === 'r') {
reload()''
} else if (char === 'R') {
secondaryReload();
}
}
});
textfield.addEventListener('keypress', (e) => {
const validChars = ['0','1','2','3','4','5'];
const char = whatkey(event).char;
if (validChars.indexOf(char) < 0)) {
event.preventDefault() // prevent the character from being input
}
});
Install
npm i -S whatkey
// or
yarn add whatkey
// or
bower install whatkey
Usage
Accessing whatkey:
import whatkey from 'whatkey';
Using whatkey:
whatkey(event)
- Takes in a keyboard event from keypress
, keyup
, or keydown
and returns an object that has the following properties:
key
- The keyboard key pressed. Does not take into account shift, so for example if you type 'A', this will contain 'a'.char
- The character created by the key press. Takes into account shift, so if you type 'A', this will contain 'A'. Note that in cases where there are multiple keys that give the same character, the simpler character is used (eg. if thekey
is "num_enter",char
will be "\n")
** whatkey.unprintableKeys
** - An array of unprintable keys (including backspace and delete, which do usually modify inputs)
Special Key and character strings
The key
and char
values contain the actual character typed ('a', '