JavaScript key handling and browser compatibility

user338195 picture user338195 · Aug 13, 2010 · Viewed 7.2k times · Source

I'm working on key handling in Javascript. I have done some research and I'd like to know whether I have a correct understanding of key handling.

KeyDown/KeyUp Event The key down and key up events are supported by IE7+ and Firefox 3.5+ I didn't check the earlier versions of the browsers, but I guess that they also support these events.

Is it correct to say that each key on the keyboard will always have a keycode.

CharCode

CharCode value is available on the keypress.Majority of the keys will have the charcodes that represent the actual value. Some keys won't have a charcode associated with them. E.g. backspace, delete, arrow keys.

Am I correct to say that on the keypress the charcode will be the same as the keycode?

Order of the events

  • KeyDown
  • KeyPress
  • KeyUp

Does this order differ from browser to browser? For example I have two functions. First is bound to KeyDown event, second is bound to the KeyPress event. Calling a KeyPress event means that the KeyDown event will also be called, when I want only one of these events to work.

Finally I have been considering on using different key handling routines depending on the version browser. For example:

  • Check browser version
  • Get key handling routine depending on the browser version

This will introduce additional code, but should simplify the maintenance. Also, in the future, when I want to provide a support for a different browser, I can simply add another routine and it won't affect existing character handling routine.

So far I have been reading http://www.quirksmode.org

Answer

gumape picture gumape · Aug 13, 2010

See the following pages, they will answer your quetions:

onkeydown event, onkeypress event, keyCode property, charCode property, which property