DOM key event confusion
There are two standard sets of events that can be used to detect key presses, the first is onkeypress and the second is both onkeyup and onkeydown. Initially I went with onkeypress for my terminal, just to keep it simple.
When you are wanting to receive presses of what are called special keys, using onkeypress
becomes a problem. In Firefox you can intercept the pressing of the backspace key, but in Internet Explorer this event never receives it and instead the browser goes back to the previously viewed page. Other keys that onkeypress does not handle in IE, include the cursor keys.
In order to work around this, I switched to onkeyup
and onkeydown
. Now all key presses, normal or special, work perfectly well in both browsers. However, there is another problem. All keys received are upper case characters, and various keys on the keyboard give symbols rather than their expected characters. The ',' key for instance gives the '¼' character.
Typing the following:
This is a test..,,,.M,,,,Gives the following output:
THIS IS A TEST¾¾¼¼¼¾M¼¼¼¼I made countless web searches trying to work out why this was. I even tried manually searching around Stack Overflow. I found web pages where someone was asking how to make the character received from
onkeydown
upper case, which implied that the problem was on my end. I was pretty much resigned to the existing behaviour, and was planning to use onkeypress to get the entered characters and onkeydown
/onkeyup
to get the special key presses. However it seemed like a hack, to work around the fact I didn't know what the problem was.A last ditch question in ##javascript on the FreeNode IRC server yielded the following information:
[16:59] <deltab> chglpnts: keydown and keyup are lower-level, just identifying which *keys* have been pressed; keypress comes later, after the specific combination of keys has been converted into a characterI wonder where this this difference is clearly stated. Searching w3.org for
[17:00] <chglpnts> deltab: Ah, I wondered if that was the case, but could find no references. How do I convert for instance 1/4 into , or is the standard way to use keydown/keyup for special keys but still use keypress for normal ones?
[17:00] <deltab> chglpnts: use both
onkeydown
does not yield any relevant pages. It is stated in the Detecting keystrokes article on the quirksmode web site, although I was unable to distinguish the meaning until I was already aware of it.In any case, I am now back on track..
No comments:
Post a Comment