When using javascript key events to add keyboard shortcuts to sites, you often end up with a big mess of unreadable code. To find out which key has been pressed, you have to check against a keycode integer. There are plans to upgrade this with DOM Level 3’s new TextInput interface, but this has not been implemented yet in major browsers.
In the meantime, it would be nice to have a way to get the current key name without much hassle.
I was playing around with Firebug trying to find an easy way of doing this and came across the native KeyboardEvent object. This is an object used by the browser to describe keyboard events. It contains a few attributes related to these events, but more importantly (for our cause), it contains a list of constants mapping names to keys. Along the lines of:
1 2 3 4 5 | |
Jackpot!
It’s a simple case of swapping the keys and values of the constants into a new object and we can now look up key names from their respective keycodes.
1 2 3 4 5 6 7 | |
The code snippet above is taken from a javascript keyboard listener I made which allows you to specify functions to run when certain key combos are pressed.