JavaScript KeyCodes and Events

When using JavaScript to detect key events in a browser, you find yourself constantly looking up keycodes for different keys. I found this list that contains a decent amount of the keycodes:

http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx

The nice thing about this website is that it allows you to enter any key into a textbox and spits out its keycode (not that that is hard to write, just conveniently placed alongside the list of codes).

When working with Keycodes and events, keep in mind that there are three different methods of capturing the key events:

1.keydown event

2.keypress event

3.keyup event

These events are quite self explanatory. In a number of cases you’ll find yourself using keypress, however keep in mind that not all key’s fire that particular event. For example, “tab” (keycode 9) only has a keyup and keydown event. Be sure to check the appropriate event you need to capture when working with key events.

Also, as another note I found interesting. It was my understanding that Keycodes where static no matter what browser you are on. This is not the case. You will find in some scenario’s that Firefox and Internet Explorer have different keyCodes for the same key. In my own experience I have only found one key that produces different codes, which is “=”. It is keycode 107 in Firefox and 187 in IE. You’ll notice this if you try out the link above in different browsers using the textbox to enter in the equals key. Here is another link that shows a number of additional keys and also a comparison between the two browsers:

http://www.aspdotnetfaq.com/Faq/What-is-the-list-of-KeyCodes-for-JavaScript-KeyDown-KeyPress-and-KeyUp-events.aspx

Leave a Reply