A translator for javascript keyboard events to and from consistent and familiar character and key representations.
MIT License
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.
myCanvas.addEventListener('keydown', (event) => {
const key = whatkey(event).key;
if (key === 'w') {
goUp();
} else if(key === 'enter') {
confirm();
} else if (key === 'shift') {
if (event.location === 1) { // left shift
shiftDown();
} else { // right shift
shiftUp();
}
} else if (key === 'backspace') {
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
}
});
npm i -S whatkey
// or
yarn add whatkey
// or
bower install whatkey
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'.key
is "num_enter", char
will be "\n")** whatkey.unprintableKeys
** - An array of unprintable keys (including backspace and delete, which do usually modify inputs)
The key
and char
values contain the actual character typed ('a', '$', '\t', etc) except in the following cases where the character isn't printable.
The string on the left is the string that represents the conceptual key/character on the right:
char
value for this will be '\b'char
value for this will be '\n'char
value for this will be '\t'char
value for this will be '0'.char
value for this will be '1'.char
value for this will be '\n'.char
value for this will be '-'.char
value for this will be '.'.char
value for this will be '/'.In handling keyboard events, keydown/keyup is almost always the best choice. However, there is at least one case where you want keypress over keydown/keyup: cases where copy/paste is used. If you ctrl-v paste some text into a field, for example, a 'keydown' event will see 'shift' and 'v' pressed, while a keypress handler will see the actual text you pasted in.
There may be other cases where keypress is necessary, but I'm not aware of them.
If you do use keypress, keep in mind that the key
value is extrapolated from the char
value, and so may not accurately represent the key pressed.
If you need accuracy for the key
, use the 'keydown' event.
Released under the MIT license: http://opensource.org/licenses/MIT