Christian Christian - 1 year ago 118
Javascript Question

Converting keystrokes gathered by onkeydown into characters in JavaScript

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.

Answer Source

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);

Here is a useful reference page.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download