Keypress is bananas

The keypress event works maddeningly differently in Chrome/Safari and Firefox, and this is the story of how I spent two hours discovering that, so that hopefully you don’t have to.

Keypress what?

A keypress event is one of the events you get when you mash on the keyboard. It’s special because according to the spec, you should only get a keypress event for keystrokes that produce printable characters. So you’ll get it for things like letters and symbols, but not for backspace and left arrow.

It’s a great event to have if you want to write some as-you-type validation on an input, and you want to be able to dismiss the non-printable characters (which will still generate key events, but are uninteresting to the validation bit).

Chrome, Safari and IE10 agree with this interpretation, which is great news.

To be contrarian, Firefox (38; I don’t know about Aurora) always sends a keypress event for anything you type. It’s basically a keydown event from what I see. Now you have to get rid of control characters yourself and you get write code that doesn’t make sense on the other platforms! Yay! (not yay)

I call shenanigans.

Mind your keyCodes and charCodes

From looking at the spec, we expect a keypress event to have:

😭

What you get out of this is spectacularly annoying. I wrote some code that basically prints out what the keypress event looks like, and found:

Chrome keypress events

Chrome keypress events

There, now you know. And knowing is half the battle.

P.S.

If you read this in the future and the future doesn’t work like I said it does, either I was wrong (highly likely), or someone fixed something. Let me know and I can make updates.