TIL: The subtle difference between Keypress and Keydown (aside from the obvious)

The other day at work, an innocuous question was posed…

So, in javascript ‘ (apostrophe) and right arrow have the same event key code. What am I supposed to do with that?

This did not seem right to me, but, sure enough, a js fiddle showed this to be true…almost (go to result tab, and hit different keyboard keys, it will show the character code).

What appeared to be the same code (if you hit apostrophe then an arrow) was actually just that the arrow didn’t register as a keypress, and you were still seeing the last keys code. However, this was only true in some browsers, IE and Chrome, Firefox I believe worked as one would expect.

Changing to a keydown event works, and shows the right arrow as 39, like it should.

Quirksmode clears up a bit of the confusion, and has a nice little tester at the bottom of the page.

Website Pin Facebook Twitter Myspace Friendfeed Technorati del.icio.us Digg Google StumbleUpon Premium Responsive