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:

WindowsMacintoshLinux
Internet Explorer7.0.5730.115.2-
Firefox2.0.0.1
(Gecko 1.8.1.1)
3.0
(Gecko 1.9)
3.0
(Gecko 1.9)
Safari3.1.23.1.1-
Opera9.109.109.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:

BrowserEvents 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:
BrowserEvents triggered on each autoreapeat
normal keysspecial 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.

BrowserWhich 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.

BrowserSide 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.1OperaKonquerorInternet Explorer
(Mac)
Shift pressedkeydown
 
keydown
 
keydown
 
 keydown
keypress
keydown
keypress
keydown
 
A pressedkeydown
keypress
keydown
keypress
keydown
keypress
keydown
keypress
keydown
keypress
keydown
keypress
keydown
keypress
A autorepeats 
keydown
keypress
 
keydown
keypress
 
 
keypress
 
 
keypress
 
 
keypress
 
 
keypress
 
A releasedkeyupkeyupkeyupkeyupkeyupkeyupkeyup
Shift releasedkeyupkeyupkeyup keyupkeyupkeyup

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.keyCodeevent.whichevent.charCode
Internet Explorer (Windows)IE keycodeundefinedundefined
Internet Explorer (Mac)IE keycodeundefinedextended ASCII code
SafariIE keycodeIE keycodeASCII code if ASCII character,
zero otherwise
GeckoMozilla keycodeMozilla keycodezero
Opera 9.50 (all platforms)
Opera 7 (Windows)
Mozilla keycode except keypad and branded keys give Opera keycodesMozilla keycode except keypad and branded keys give Opera keycodesundefined
Opera 8.0 to 9.27 (Windows)Opera keycodeOpera keycodeundefined
Opera < 9.50 (Linux & Macintosh)Pseudo-ASCII codePseudo-ASCII codeundefined
Konqueror 3.5Pseudo-ASCII codePseudo-ASCII code if key has an ASCII code,
zero otherwise
zero
Konqueror 3.2Pseudo-ASCII codePseudo-ASCII codeundefined
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.keyCodeevent.whichevent.charCode
Internet Explorer (Windows)normal:ASCII codeundefinedundefined
special:no keypress events for special keys
Internet Explorer (Mac)normal:ASCII codeundefinedASCII code
special:no keypress events for special keys
Geckonormal:zeroASCII codeASCII code
special:Mozilla keycodezerozero
Safari 3.1normal:ASCII codeASCII codeASCII code
special:no keypress events for special keys
Safari < 3.1normal:ASCII codeASCII codeASCII code
special:extended ASCII codeextended ASCII codeextended ASCII code
Opera 9.50 (all platforms)
Opera 7 (Windows)
normal:ASCII codeASCII codeundefined
special:Mozilla keycode, except keypad and branded keys give Opera keycodeszero for arrows, function keys, PageUp, PageDown
same as event.keyCode otherwise
undefined
Opera 8.0 to 9.27 (Windows)normal:ASCII codeASCII codeundefined
special:Opera keycodezero for arrows, function keys, PageUp and PageDown,
same as event.keyCode otherwise
undefined
Opera < 9.50 (Linux & Macintosh)normal:ASCII codeASCII codeundefined
special:Opera keycodezero for arrows, function keys, PageUp and PageDown,
same as event.keyCode otherwise
undefined
Konqueror 3.5normal:ASCII codeASCII codeASCII code
special:Pseudo-ASCII codezerozero
Konqueror 3.2normal:ASCII codeASCII codeundefined
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.

KeyASCIIMozilla keycodesIE keycodesOpera keycodespseudo ASCII codesexceptions
Alphabetic keys
A to Z
97/65 to 122/90ASCII code of uppercase version of the letter
65 to 90
Space3232323232
Enter1313131313
Tab99999
Esc2727272727
Backspace88888
Modifier Keys
KeyASCIIMozilla keycodesIE keycodesOpera keycodespseudo ASCII codesexceptions
Shift-16161616Linux Opera < 9.0: 0
Control-17171717Linux Opera < 9.0: 0
Mac Opera: 0
Alt-18181818Linux Opera < 9.0: 0
Caps Lock-20202020Linux Opera: 0
Num Lock-144144144144Linux Opera < 9.50: 0
Win Opera < 9.00: 0
Keyboard Number Keys
KeyASCIIMozilla keycodesIE keycodesOpera keycodespseudo ASCII codesexceptions
1 !49/3349494949/33Mac Gecko < 1.8: 49/0
2 @50/6450505050/64Mac Gecko < 1.9: 50/0
3 #51/3551515151/35Mac Gecko < 1.9: 51/0
4 $52/3652525252/36Mac Gecko < 1.9: 52/0
5 %53/3753535353/37Mac Gecko < 1.9: 53/0
6 ^54/9454545454/94Mac Gecko < 1.9: 54/0
7 &55/3855555555/38Mac Gecko < 1.9: 55/0
8 *56/4256565656/42Mac Gecko < 1.9: 56/0
9 (57/4057575757/40Mac Gecko < 1.9: 57/0
0 )48/4148484848/41Mac Gecko < 1.9: 48/0
Symbol Keys
KeyASCIIMozilla keycodesIE keycodesOpera keycodespseudo ASCII codesexceptions
; :59/58591865959/58Mac Gecko: 186/0
= +61/43611876161/43Mac Gecko 1.9: 187/107
Mac Gecko < 1.9: 187/0
, <44/601881884444/60Mac Gecko: 188/0
- _45/951091894545/95Mac Gecko 1.9: 109/0
Mac Gecko < 1.9: 0
. >46/621901904646/62Mac Gecko: 190/0
/ ?47/631911914747/63Mac Gecko: 191/0
` ~96/1261921929696/126Mac Gecko: 126/0
[ {91/1232192199191/123
\ |92/1242202209292/124Mac Gecko: 92/0
] }93/1252212219393/125
' "39/342222223939/34
Arrow Keys
KeyASCIIMozilla keycodesIE keycodesOpera keycodespseudo ASCII codesexceptions
left-arrow-37373737
up-arrow-38383838
right-arrow-39393939
down-arrow-40404040
Special Keys
KeyASCIIMozilla keycodesIE keycodesOpera keycodespseudo ASCII codesexceptions
Insert-45454545Konqueror: 0
Opera < 9.0: 0
Delete-46464646Konqueror: 127
Opera < 9.0: 0
Home-36363636Opera < 9.0: 0
End-35353535Opera < 9.0: 0
Page Up-33333333
Page Down-34343434
Function Keys
F1 to F12
-112 to 123112 to 123112 to 123112 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.
KeyASCIIMozilla keycodesIE keycodesOpera keycodespseudo ASCII codesexceptions
. Del46/-110/46110/4678/4678/46Opera < 9.0: 78/0
0 Ins48/-96/4596/4548/4548/45Opera < 9.0: 48/0
1 End49/-97/3597/3549/3549/35Opera < 9.0: 49/0
2 down-arrow50/-98/4098/4050/4050/40
3 Pg Dn51/-99/3499/3451/3451/34
4 left-arrow52/-100/37100/3752/3752/37
553/-101/12101/1253/1253/12Linux Opera: 53/0
6 right-arrow54/-102/39102/3954/3954/39
7 Home55/-103/36103/3655/3655/36Opera < 9.0: 55/0
8 up-arrow56/-104/38104/3856/3856/38
9 Pg Up57/-105/33105/3357/3357/33
+431071074343
-451091094545
*421061064242
/471111114747
Keypad Enter1313131313
Branded Keys
KeyASCIIMozilla keycodesIE keycodesOpera keycodespseudo ASCII codesexceptions
Left Apple Command-224?17?Safari 3.1: 91
Right Apple Command-224?17?Safari 3.1: 93
Left Windows Start-91912190Linux Gecko: 0
Right Windows Start-92922200Linux Gecko: 0
Windows Menu-939300
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.

keyExtended ASCII codes for Special Keys
up arrowdown arrowleft arrowright arrowfunction keys
F1 to F12
HomeEndPage UpPage Down
Safari < 3.16323263233632346323563236 to 6324763273632756327663277
Macintosh IE3031282916 for all keysno 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.

keysKeycodes on Gecko keyup and keydown events
Linux and Windows
Gecko (correct)
Macintosh Gecko 1.8 and olderMacintosh Gecko 1.9
! @ # $ % ^ & * ( )Same as number keys these symbols appear onzeroSame as number keys these symbols appear on
-109zero109
_ ~ | < > ? :Same as unshifted symbol keys these symbols appear onzerozero
+61zero107
Any key typed with ALT key held downSame code as without ALT keyzeroSame 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.

转载于:https://www.cnblogs.com/qindgfly/archive/2008/08/07/1263021.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值