tags:

views:

206

answers:

1

I try to convert keystrokes into chracters. In other question someone recommand to use the onkeydown function because onkeypress gets handeled differently by different characters.

I don't know how to handle special chracters like ´ ` ' ( ) that might be different in different keyboards around the world.

+2  A: 

For keys that have printable character equivalents, you should use the keypress event because you can retrieve character codes from the keypress event, which is generally not possible for keyup and keydown events.

The event properties you need are which and keyCode - pretty much all browsers have one or both of these, though IE muddies the waters by using keyCode for the character code while some other browsers return a (different) key code. Most non-IE browsers also have charCode but it seems all such browsers also have which, so charCode is never needed. A simple example:

document.onkeypress = function(evt) {
  evt = evt || window.event;
  var charCode = evt.which || evt.keyCode;
  var charStr = String.fromCharCode(charCode);
  alert(charStr);
};

Here is a useful reference page.

Tim Down
Basically that means that I have to handle printable chracters with onkeypress and the rest (like the delete key) with onkeydown?
Christian
Yes. If it's just the delete key it should be fine - I believe the keyCode is 46 in most browsers and keyboards.
Tim Down