So we have charCode, keyIdentifier, and keyCode along with keyup, keydown, and keypress – is there a solution that we can safely use in a cross-browser manner?
Yehuda: There’s a reasonably good writeup at: http://unixpapa.com/js/key.html. Effectively, you can use e.keyCode for all modern browsers in keydown/keyup (although you’ll need to consult the chart at the bottom of that page to determine whether the keyCodes returned by the browsers are consistent). For keypress, e.charCode || e.keyCode should work (Mozilla and Safari define e.charCode, while IE defines e.keyCode which returns the ASCII value). What that means is that you have a close-to-cross-browser keyCode for keyup/keydown and a pretty reasonable charCode for keypress. As a result, keypress can be used for key events that produce text for which you need to know its ASCII value (A vs. a). keyup/keydown can be used for events for which you care about the physical key that was pressed. Again, there are some quirks, which can be summed up in the tables at http://unixpapa.com/js/key.html.
Related Questions
- So we have charCode, keyIdentifier, and keyCode along with keyup, keydown, and keypress - is there a solution that we can safely use in a cross-browser manner?
- Can mothers safely prepare labon-gur salt-sugar solution after demonstration in a diarrhoeal hospital?
- How Do You Safely Make Lye Solution For Soap?