Javascript Keyboard Events

JavaScript Madness: Keyboard Events

Jan Wolter
July 7, 2008

1. Introduction

This document summarizes the results of some browser tests done while attempting to implement key stroke handling code in JavaScript. It documents inconsistancies in the way different browsers implement keyboard events.

The tests were originally done with the intention of learning just enough to write the code I needed to write. Coverage has expanded considerably since then, but the results here still are not comprehensive or authoritative and do not cover all aspects of keyboard event handling.

This data is based on a limited number of tests on a limited number of browsers. The browser versions most recently tested are:

Windows Macintosh Linux
Internet Explorer 7.0.5730.11 5.2 -
Firefox 2.0.0.1
(Gecko 1.8.1.1)
3.0
(Gecko 1.9)
3.0
(Gecko 1.9)
Safari 3.1.2 3.1.1 -
Opera 9.10 9.10 9.27
Konqueror - - 3.5.7
This document does not cover the behavior of keypad keys on the Macintosh, because none of my Macs have keypads.

This document will usually refer to "Gecko" instead of "Firefox" to better include all the other browsers based on Gecko that behave similarly to Firefox. See the Gecko version table page for more information.

Previous versions of this document included coverage of the iCab 3 browser, but more recent versions of iCab use the same rendering engine as Safari, and so presumably behave exactly like Safari. Since it is unlikely that many web developers will want to go out of their way to support iCab 3, that material has been removed from this document and archived in a separate report on iCab 3.

The script used to collect the test results reported here is available at http://unixpapa.com/js/testkey.html.

2. Event Triggering

In all recent browsers, pressing a key triggers a series of Javascript events which can be captured and handled. These events, however, were not defined by any standard until DOM3 which few browsers have yet implemented.

In every browser tested, there were three events triggered when a key was pressed and released:

keydown
keypress
keyup

The keydown event occurs when the key is pressed, followed immediately by the keypress event. Then the keyup event is generated when the key is released.

To understand the difference between keydown and keypress, it is useful to distinguish between "characters" and "keys". A "key" is a physical button on the computer's keyboard. A "character" is a symbol typed by pressing a button. On a US keyboard, hitting the 4 key while holding down the Shift key typically produces a "dollar sign" character. This is not necessarily the case on every keyboard in the world. In theory, the keydown and keyup events represent keys being pressed or released, while the keypress event represents a character being typed. In practice, this is not always the way it is implemented.

Note that DOM3 defines only the keydown and keyup events, not keypress. Instead of keypress it defines a new event called textinput, which is sort of a generalization of keypress which is supposed to fire whenever text is input, whether by keyboard or not (it could be spoken text or cut/pasted text). So far as I know, no browser yet supports textinput.

2.1. Events Triggered by Special Keys

In addition to all the normal keys used to input ASCII characters, keyboard typically have many special purpose keys that do other things. These do not necessarily generate the same events as normal keys, and they show less consistency across browsers.

"Modifier keys" are one class of special keys. They include keys like Shift, Control and Alt, that don't send characters, but modify the characters sent by other keys. For most browsers, both keydown and keyup events are triggered by modifier keys, but keypress events are not. This is consistant with their being "key" events not "character" events. However, there is a lot of variation:

Browser Events sent when modifier keys are typed
Gecko 1.7 and later
Internet Explorer
Safari 3.1
keydown
keyup
Opera
Konqueror
keydown
keypress
keyup
Safari < 3.1
Gecko 1.6
no events sent

Most browsers treat the Caps Lock key the same as any other modifier key, sending keydown when it is depressed and keyup when it is released, but Macintosh versions of Safari 3 are a bit cleverer: each time you strike and release the key, only one event is triggered, and it is keydown if you turning on caps-lock mode and keyup if you are turning it off. Safari does not do this with Num Lock.

There are many other special keys on a typical keyboard that do not normally send characters. These include the four arrow keys, navigation keys like Home and Page Up, special function keys like Insert and Delete, and the function keys F1 through F12. Internet Explorer and Safari 3.1 seem to classify all of these with the modifier keys, since they generate no text, so in those browsers there is no keypress event for them, only keyup and keydown. Many other browsers do generate keypress events for these keys, however.

Old versions of Safari had a bug that caused two identical keyup events to be triggered when arrow keys and other special keys were released. I know this existed in Safari 1.3 and I know it is fixed in Safari 3.1, but I don't know when it was fixed.

Standard Windows keyboards typically have two Start keys and a Menu key, while Apple keyboards have two Apple keys. I'm not going to attempt to describe the behavior of those keys in detail here. They are very inconsistent across browsers, don't exist on all keyboards, and they frequently have default actions that cannot be disabled. As such, Javascript programmers are probably well advised to stay away from them.

If NumLock is off, and you hit keypad number key while holding Shift down, then Windows systems trigger some extra events. Windows browsers pretend that the Shift key was released before the key was typed, and then pressed again after it was released, and they trigger keyup, keydown and (in some browsers) keypress events to indicate this. Linux systems don't do this. I don't know if Macintoshes do.

2.2. Events Triggered on Auto-Repeat

If a key is held down long enough it typically auto-repeats, and some additional events will be triggered on each autorepeat. On Macintosh and Linux systems, modifier keys usually don't auto-repeat, but on Windows systems they do (which seems weird to me). In most browsers, an autorepeat is sensibly treated as a character event, but not a key event, so it triggers a keypress but not a keydown or keyup. But, of course, there is some variation:
Browser Events triggered on each autoreapeat
normal keys special keys
Internet Explorer (Windows)
Safari 3.1
keydown
keypress
keydown
Gecko (Windows) keydown
keypress
Gecko (Linux)
Gecko (Macintosh)
Safari < 3.1
Konqueror
Opera
keypress only
Internet Explorer (Macintosh) no events triggered

2.3. Suppressing Default Event Handling

If you are installing your own handlers for key events, then sometimes you won't want the browser default action to occur (such as having the character appear in a text entry area). To prevent this, you typically have the event handler return false, and maybe call event.preventDefault() and event.stopPropagation() if they are defined. But on which event handler must you suppress defaults? This, of course, varies from browser to browser.

Browser Which event handlers need to suppress defaults to prevent key from appearing in text box
Internet Explorer
Gecko
Safari
either keydown or keypress
Opera
Konqueror 3.5
keypress
Konqueror 3.2 keydown

Suppressing defaults on the keydown event has some odd side effects on some browsers, in that it may prevent some other events from firing. Apparantly, triggering further events is taken to be part of the default action of the keydown event in these browsers.

Browser Side effect if keydown handler returns false
Gecko
Safari < 3.1
Opera
No change
Internet Explorer
Safari 3.1
keypress event never occurs.
keyup event works normally.
Konqueror keypress event only occurs on auto repeats.
keyup event works normally.
Most applications will either use only keypress or use only keyup/keydown, so this all works out pretty well in most browsers. If you are handling keypress and want to suppress default handling of the key, return false from that handler. If you are handling keydown/keyup and want to suppress defaults, install a keypress handler that does nothing except return false.

The DOM3 standards say that keyup should still occur if the default action on keydown is suppressed, but textinput should not.

2.4. Event Triggering Summary

To give a clearer side by side comparison, suppose we press the Shift key, then press the A key, holding it down long enough to auto-repeat just once, then release A, and the release Shift. The events we see are shown below for various browsers. Events marked in red do not occur if there is a keydown handler that returns false.
Internet Explorer
(Windows)
Safari 3.1
Gecko
(Windows)
Gecko
(Linux/Mac)
Safari < 3.1 Opera Konqueror Internet Explorer
(Mac)
Shift pressed keydown
 
keydown
 
keydown
 
  keydown
keypress
keydown
keypress
keydown
 
A pressed keydown
keypress
keydown
keypress
keydown
keypress
keydown
keypress
keydown
keypress
keydown
keypress
keydown
keypress
A autorepeats  
keydown
keypress
 
keydown
keypress
 
 
keypress
 
 
keypress
 
 
keypress
 
 
keypress
 
A released keyup keyup keyup keyup keyup keyup keyup
Shift released keyup keyup keyup   keyup keyup keyup

At this point, this document used to exclaim about how no two browsers behaved alike, but Apple's WebKit developers made a major effort to improve their handling of key events, so now we see Safari behaving identically with IE. Kudos to the WebKit folks.

3. Identifying Keys

When you catch a keyboard event, you may wish to know which key was pressed. If so, you may be asking too much. This is a very big mess of browser incompatibilities and bugs.

3.1. Values Returned on Key Events

The keydown and keyup events should return a code identifying a key, not a code identifying a character. It is not obvious how to do this. ASCII codes don't really suffice, since the same key can generate different characters (if combined with shift or control), and the same character can be generated by different keys (such as the numbers on the keyboard and the numbers on the keypad). Different browsers use different ways of assigning numeric codes to the different keys. We will call these "Mozilla keycodes", "IE keycodes", "Opera keycodes" and "psuedo-ASCII codes" and we'll explain them in more detail below.

Not only do the browsers differ in what values they return, they differ in where they return them. Three different properties of the event object may be used to return them. They are event.keyCode, event.which and event.charCode.

keydown and keyup events
event.keyCode event.which event.charCode
Internet Explorer (Windows) IE keycode undefined undefined
Internet Explorer (Mac) IE keycode undefined extended ASCII code
Safari IE keycode IE keycode ASCII code if ASCII character,
zero otherwise
Gecko Mozilla keycode Mozilla keycode zero
Opera 9.50 (all platforms)
Opera 7 (Windows)
Mozilla keycode except keypad and branded keys give Opera keycodes Mozilla keycode except keypad and branded keys give Opera keycodes undefined
Opera 8.0 to 9.27 (Windows) Opera keycode Opera keycode undefined
Opera < 9.50 (Linux & Macintosh) Pseudo-ASCII code Pseudo-ASCII code undefined
Konqueror 3.5 Pseudo-ASCII code Pseudo-ASCII code if key has an ASCII code,
zero otherwise
zero
Konqueror 3.2 Pseudo-ASCII code Pseudo-ASCII code undefined
In version 9.50, Opera abandoned Opera keycodes and Pseudo-ASCII keycodes in favor of Mozilla keycodes for most keys (thus reverting to the behavior of Windows Opera 7). Safari has modified their Konqueror-derived code to use IE keycodes, and I expect Konqueror will follow. Thus there seems to be a convergences on the IE and Mozilla keycodes, which are pretty similar. This is kind of encouraging.

On keydown and keyup, the event objects also have flags that indicate which modifier keys were being pressed when the key was typed. These are:

   event.shiftKey

   event.ctrlKey

   event.altKey

   event.metaKey

These all have true or false values. According to the DOM 3 standard, on the Macintosh, the Option key should activate event.altKey and the Command key should activate event.metaKey. These attributes seem to work correctly on all browsers tested, except event.metaKey is undefined in all versions IE (in Mac versions of IE, the Command key sets event.ctrlKey and the Control key does nothing).

One would think that if a key is typed when Caps Lock is on, then event.shiftKey would be true, but this is not the case in any browser tested. There is also a lot of inconsistency in the values these flags take on the keydown and keyup events actually associated with pressing and releasing the modifier keys, but I can't imagine anyone would care enough to justify documenting the details.

The DOM3 standard abandons all hope of creating order among event.keyCode, event.which and event.charCode, and instead defines new values for keydown and keyup events, event.keyIdentifier and event.keyLocation. The keyIdentifier is a string that in most cases looks like "U+0041" where the "0041" part is the unicode value of the character sent by the key when it is typed without modifiers, in this case the letter "A". For keys that don't send unicode characters, or where the unicode value is not standardized, it is a string like "Enter", "Shift", "Left" or "F9". A complete list is here. The keyLocation value gives values to distinguish among multiple keys that have the same identifier, like the left and right shift keys, or the keypad number keys. It is 0 for standard keys, 1 or 2 for left or right versions of a keys like Shift which appear twice on the keyboard, and 3 for keys on the numeric keypad.

Safari supports keyIdentifier and gets it mostly right. Older versions conformed to an older version of the standard and returned two extra zeros (eg, "U+000041") but this was corrected in version 3.1. Windows versions of Safari return bad keyIdentifier values for all of the non-number symbol keys. The keyLocation attribute is always 0 or 3, so it does not distinguish between left and right modifier keys.

Konqueror returns keyIdentifier values like "Shift" and "Enter" correctly, but instead of returning the Unicode values, it returns the typed character itself, "a" or "A" instead of "U+0041". All keyLocation values are zero, except for modifiers key, which are always one, regardless of whether the left or right one was pressed.

No other browsers that I have tested support keyIdentifier or keyLocation at all.

3.2. Values Returned on Character Events

For keypress events, it is pretty clear that the ASCII code of the typed character should be returned, and pretty much all browsers do that.

But what if there is no ASCII code associated with the key? Arrow keys and keys like Page Down and F1 don't have ASCII codes. We call these "special" keys in contrast to the "normal" keys that have ASCII codes. Note that Esc, Backspace, Enter, and Tab are "normal" because they have ASCII codes.

When keypress events are generated for special keys, the browser needs to return some non-ASCII value to indicate which key ways pressed. We'll see that various different browsers do this in different ways.

Some browsers avoid this problem by not generating keypress events for special keys. A good case can be made that this is the right thing to do, since these keystrokes are arguably not character events. But such arguments are weakened by the arbitrariness of the division between normal and special keys. Why should the keyboard Backspace key have a keypress event, but not the keypad Delete key? Is Tab really fundamentally different than right arrow?

keypress events
event.keyCode event.which event.charCode
Internet Explorer (Windows) normal: ASCII code undefined undefined
special: no keypress events for special keys
Internet Explorer (Mac) normal: ASCII code undefined ASCII code
special: no keypress events for special keys
Gecko normal: zero ASCII code ASCII code
special: Mozilla keycode zero zero
Safari 3.1 normal: ASCII code ASCII code ASCII code
special: no keypress events for special keys
Safari < 3.1 normal: ASCII code ASCII code ASCII code
special: extended ASCII code extended ASCII code extended ASCII code
Opera 9.50 (all platforms)
Opera 7 (Windows)
normal: ASCII code ASCII code undefined
special: Mozilla keycode, except keypad and branded keys give Opera keycodes zero for arrows, function keys, PageUp, PageDown
same as event.keyCode otherwise
undefined
Opera 8.0 to 9.27 (Windows) normal: ASCII code ASCII code undefined
special: Opera keycode zero for arrows, function keys, PageUp and PageDown,
same as event.keyCode otherwise
undefined
Opera < 9.50 (Linux & Macintosh) normal: ASCII code ASCII code undefined
special: Opera keycode zero for arrows, function keys, PageUp and PageDown,
same as event.keyCode otherwise
undefined
Konqueror 3.5 normal: ASCII code ASCII code ASCII code
special: Pseudo-ASCII code zero zero
Konqueror 3.2 normal: ASCII code ASCII code undefined
special: no keypress events for special keys
The best method to distinguish special keys from normal keys on keypress events is to first check event.which. If it is undefined or non-zero, then the event is from a normal key, and the ASCII code for that key is in event.keyCode. If it is defined as zero, the the event is from a special key, and the key code is in event.keyCode. This works for every browser except Opera, which messes up by returning non-zero event.which values for some special keys ( Insert, Delete, Home and End).

However, if you are actually interested in special key events, then probably you should be hooking your code into keydown and keyup, which work more consistently across browsers. So the main practical importance of this is that keypress handlers should not treat event.keyCode as an ASCII code if event.which is defined and zero.

The flags event.shiftKey, event.ctrlKey, event.altKey and event.metaKey are typically defined on keypress events, just as they are on keydown and keyup events. Safari seems to define event.keyIdentifier on keypress as well, but I wouldn't count on future browsers doing that.

3.3. Key Code Values

Now for the actual values being returned for different keys. Some people refer to the Mozilla/IE keycodes as "scan codes". Scan codes are returned from the keyboard, and are converted to ASCII by the keyboard drivers. They typically vary with different kinds of keyboards. As far as I can tell, these are NOT scan codes. They vary with the browser type rather more than with keyboard type, and they don't seem to match with any keyboard scan codes that I've seen documented.

The table below lists values for keys commonly found on US keyboards. If a single value is given, then that value is sent whether the Shift key is held down or not. If two values x/y are given, the the first is sent when the key is unshifted, and the second is sent when the key is shifted. (Ideally there should be slashed values only in the ASCII column of this table, since these the other codes are all used only on keyup and keydown events, which are key events not character events.)

Keys highlighted in green are consistent across all browsers tested. Keys highlighted in yellow are consistent for recent versions of IE, Gecko, Safari and Opera. Keys highlighted in red aren't.

Key ASCII Mozilla keycodes IE keycodes Opera keycodes pseudo ASCII codes exceptions
Alphabetic keys
A to Z
97/65 to 122/90 ASCII code of uppercase version of the letter
65 to 90
Space 32 32 32 32 32
Enter 13 13 13 13 13
Tab 9 9 9 9 9
Esc 27 27 27 27 27
Backspace 8 8 8 8 8
Modifier Keys
Key ASCII Mozilla keycodes IE keycodes Opera keycodes pseudo ASCII codes exceptions
Shift - 16 16 16 16 Linux Opera < 9.0: 0
Control - 17 17 17 17 Linux Opera < 9.0: 0
Mac Opera: 0
Alt - 18 18 18 18 Linux Opera < 9.0: 0
Caps Lock - 20 20 20 20 Linux Opera: 0
Num Lock - 144 144 144 144 Linux Opera < 9.50: 0
Win Opera < 9.00: 0
Keyboard Number Keys
Key ASCII Mozilla keycodes IE keycodes Opera keycodes pseudo ASCII codes exceptions
1 ! 49/33 49 49 49 49/33 Mac Gecko < 1.8: 49/0
2 @ 50/64 50 50 50 50/64 Mac Gecko < 1.9: 50/0
3 # 51/35 51 51 51 51/35 Mac Gecko < 1.9: 51/0
4 $ 52/36 52 52 52 52/36 Mac Gecko < 1.9: 52/0
5 % 53/37 53 53 53 53/37 Mac Gecko < 1.9: 53/0
6 ^ 54/94 54 54 54 54/94 Mac Gecko < 1.9: 54/0
7 & 55/38 55 55 55 55/38 Mac Gecko < 1.9: 55/0
8 * 56/42 56 56 56 56/42 Mac Gecko < 1.9: 56/0
9 ( 57/40 57 57 57 57/40 Mac Gecko < 1.9: 57/0
0 ) 48/41 48 48 48 48/41 Mac Gecko < 1.9: 48/0
Symbol Keys
Key ASCII Mozilla keycodes IE keycodes Opera keycodes pseudo ASCII codes exceptions
; : 59/58 59 186 59 59/58 Mac Gecko: 186/0
= + 61/43 61 187 61 61/43 Mac Gecko 1.9: 187/107
Mac Gecko < 1.9: 187/0
, < 44/60 188 188 44 44/60 Mac Gecko: 188/0
- _ 45/95 109 189 45 45/95 Mac Gecko 1.9: 109/0
Mac Gecko < 1.9: 0
. > 46/62 190 190 46 46/62 Mac Gecko: 190/0
/ ? 47/63 191 191 47 47/63 Mac Gecko: 191/0
` ~ 96/126 192 192 96 96/126 Mac Gecko: 126/0
[ { 91/123 219 219 91 91/123
\ | 92/124 220 220 92 92/124 Mac Gecko: 92/0
] } 93/125 221 221 93 93/125
' " 39/34 222 222 39 39/34
Arrow Keys
Key ASCII Mozilla keycodes IE keycodes Opera keycodes pseudo ASCII codes exceptions
left-arrow - 37 37 37 37
up-arrow - 38 38 38 38
right-arrow - 39 39 39 39
down-arrow - 40 40 40 40
Special Keys
Key ASCII Mozilla keycodes IE keycodes Opera keycodes pseudo ASCII codes exceptions
Insert - 45 45 45 45 Konqueror: 0
Opera < 9.0: 0
Delete - 46 46 46 46 Konqueror: 127
Opera < 9.0: 0
Home - 36 36 36 36 Opera < 9.0: 0
End - 35 35 35 35 Opera < 9.0: 0
Page Up - 33 33 33 33
Page Down - 34 34 34 34
Function Keys
F1 to F12
- 112 to 123 112 to 123 112 to 123 112 to 123
Keypad Keys
If Num Lock is on, unshifted/shifted values are returned as shown below. If Num Lock is off, Linux browsers reverse the shifted/unshifted values, while Windows browsers always return the shifted value. None of my Macintoshs have a keypad, so I don't know what they do.
Key ASCII Mozilla keycodes IE keycodes Opera keycodes pseudo ASCII codes exceptions
. Del 46/- 110/46 110/46 78/46 78/46 Opera < 9.0: 78/0
0 Ins 48/- 96/45 96/45 48/45 48/45 Opera < 9.0: 48/0
1 End 49/- 97/35 97/35 49/35 49/35 Opera < 9.0: 49/0
2 down-arrow 50/- 98/40 98/40 50/40 50/40
3 Pg Dn 51/- 99/34 99/34 51/34 51/34
4 left-arrow 52/- 100/37 100/37 52/37 52/37
5 53/- 101/12 101/12 53/12 53/12 Linux Opera: 53/0
6 right-arrow 54/- 102/39 102/39 54/39 54/39
7 Home 55/- 103/36 103/36 55/36 55/36 Opera < 9.0: 55/0
8 up-arrow 56/- 104/38 104/38 56/38 56/38
9 Pg Up 57/- 105/33 105/33 57/33 57/33
+ 43 107 107 43 43
- 45 109 109 45 45
* 42 106 106 42 42
/ 47 111 111 47 47
Keypad Enter 13 13 13 13 13
Branded Keys
Key ASCII Mozilla keycodes IE keycodes Opera keycodes pseudo ASCII codes exceptions
Left Apple Command - 224 ? 17 ? Safari 3.1: 91
Right Apple Command - 224 ? 17 ? Safari 3.1: 93
Left Windows Start - 91 91 219 0 Linux Gecko: 0
Right Windows Start - 92 92 220 0 Linux Gecko: 0
Windows Menu - 93 93 0 0
Note that all four encodings agree on most of the common keys, the ones highlighted in green in this table. For the letters and numbers and for spaces, tabs, enters, and arrows the codes are all the same. In fact, they are all standard ASCII values (except for the arrows).

For symbols, things are a fair mess. IE and Mozilla don't entirely agree on what the codes should be. Three keys, ; :, = + and - _, have different values in IE and Mozilla keycodes. Furthermore, there are long standing bugs in Macintosh versions of Gecko that have caused zero keyCodes to be returned for many symbols.

The Opera keycodes have been abandoned by Opera, but they had a certain simple charm. They were always the ASCII code of the character that the key sends when it is not modified by shift or control. They don't allow you to distinguish numbers typed on the keypad from numbers typed on the keyboard, and such like things, but they are, at least, fairly intuitive.

The pseudo ASCII codes weren't really key codes at all. They were just the ASCII code for the character except that for lower case letters the upper case ASCII code is sent. So those browsers really entirely abandoned the idea of keycodes, instead returning character codes slightly modified for partial IE compatibility. There is much to be said for abandoning key codes, since the concept really gets you in trouble as you try to handle international keyboards, but something is lost when you do that. You can't, for example, tell if a number was typed on the main keyboard or the keypad. I prefer Safari's approach, where they keep the keycodes (making them entirely compatible with IE keycodes) but also return the character code on all key events.

Using pseudo-ASCII codes causes another problem: you can't always recognize the arrow keys on keydown and keyup events. These browsers send the same codes as IE does for arrow keys: the values 37, 38, 39, and 40. These happen to be the ASCII codes for "%", "&", "'" and "(". In the keycode schemes this isn't a problem, because those characters are all produced by shifted keys, so those codes would never be produced as a keycode. But when pseudo-ASCII keycodes are used these same values are also sent when you type those keys, so you can't tell those symbols from arrow keys. Similar problems occur with some of the other special keys like Home which sends the same values as "$".

For browsers that generate keypress events for special keys, it is also generally true that event.keyCode will have the same value for "left-arrow" and "%", however we can usually tell which it is because event.which is zero for special keys (this doesn't work for all keys in Opera). Versions of Safari before 3.1 took a different approach. They invented unique values to return instead of ASCII codes for special keys, and returned the same value in event.keyCode, event.which, and event.charCode. The table below gives the extended ASCII codes returned by old Safari versions, and also the ones returned in event.charCode on keydown and keyup events in Macintosh versions of IE.

key Extended ASCII codes for Special Keys
up arrow down arrow left arrow right arrow function keys
F1 to F12
Home End Page Up Page Down
Safari < 3.1 63232 63233 63234 63235 63236 to 63247 63273 63275 63276 63277
Macintosh IE 30 31 28 29 16 for all keys no events triggered

To complete the thoroughness of the mess, keycode generation in current Macintosh versions of Gecko remains buggy. For many keys, no key codes are returned on keydown and keyup events. Instead the keyCode value is just zero. Some of these problems were fixed in Gecko 1.9, but not all, and the keyboard plus key started returning the value that is supposed to be returned by the number pad plus key.

keys Keycodes on Gecko keyup and keydown events
Linux and Windows
Gecko (correct)
Macintosh Gecko 1.8 and older Macintosh Gecko 1.9
! @ # $ % ^ & * ( ) Same as number keys these symbols appear on zero Same as number keys these symbols appear on
- 109 zero 109
_ ~ | < > ? : Same as unshifted symbol keys these symbols appear on zero zero
+ 61 zero 107
Any key typed with ALT key held down Same code as without ALT key zero Same code as without ALT key
Macintosh Gecko does give correct charCode values on keypress events, but to a keydown or keyup handler, all the keys that return zero above are indistinguishable. This bug was reported to Mozilla (bug 44259) in June 2000, and it took eight years to get the partial fixes out. Who knows when it will really be fixed.

Conclusions

It's truely impressive what a hash has been made of a simple thing like recognizing a key pressed on the keyboard. You'd think computer technology would have advanced far enough by now to have this all worked out better.

The keypress events are generally the easiest to work with. It's usually easy to identify which key was pressed. You can get the character typed by doing:

  if (event.which == null

     char= String.fromCharCode(event.keyCode);    // IE

  else if (event.which > 0)

     char= String.fromCharCode(event.which);	  // All others

  else

     // special key

What to do with keypress events on special keys is a problem. I recommend pretending they never happened. If you really want to process special key events, you should probably be working with keydown and keyup instead.

For keydown and keyup events, you can identify most common keys (letters, numbers, and a few others) by just looking at the event.keyCode and more or less pretending that it is an ASCII code. However, it isn't really, and the many Javascript manuals that say it can be converted to a character by doing "String.fromCharCode(event.keyCode)" are wrong. On keydown and keyup events, the key codes are not character codes, and this conversion will give wild results for many keys. There is no general portable way to convert keycodes to characters. You pretty much have to sense the browser type and base the key mapping on that.

Because of bugs, many keys cannot be distinguished on keydown and keyup in Macintosh Gecko.

Hope for sanity exists, with DOM3, but it has not yet arrived.

你可能感兴趣的:(JavaScript)