Simple question — Does anyone know of a reliable cross-browser function to get the character typed from a keydown event? I can write one from the quirksmode grid but would rather not re-invent the wheel for something so simple yet so non-standard.
Let me clarify:
There is no way to do this simply using event.keyCode or event.which. The overall logic is something like:
- get keycode
- detect shift, ctrl
- if ctrl, ignore
- create map of keycodes with and without shift key
- example map
{186 : ';', 187 : '=', 188 : ',', ....} - need a separate map for shift key modifier
- map needs to change depending on browser (especially Safari Mac which has keycodes like 60,000)
- example map
- if keycode is in map, return mapped key
- if keycode is not in map, normalize numbers, apply shift modifier key if necessary, return
String.fromCharCode(key)
It’s not a simple solution, which is why I’m looking for a pre-made one 🙂
Are you willing to use jQuery?
I believe that switching to the keypress event would solve the issue mentioned in your comment. Would the code below meet your requirments?