Convert keystrokes by character in JavaScript

I am trying to convert keystrokes to cams. In another question, someone recommends using the onkeydown function because onkeypress is handled differently by different characters.

I don't know how to handle special fists like '' '(), which may be different on different keyboards around the world.

+2


source to share


2 answers


For keys with printable character equivalents, you must use an event keypress

because you can extract character codes from an event keypress

, which is usually not possible with events keyup

and keydown

.

Required event properties which

and keyCode

- almost all browsers have one or both of these, although IE is confused by the use of keyCode

for character code, while some other browsers return (different) key code. Most browsers other than IE also have charCode

, but it looks like all such browsers do which

, so it is charCode

never required. 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 helpful help page .

+7


source


 document.onkeydown = checkKey;
function checkKey(e) {

e = e || window.event;
document.getElementById("label").style.display = "none";
if (e.keyCode == '65') {
    //a
    var lx = document.getElementById('location');
    typeIt("a");
}
else if (e.keyCode == '66') {
    //b
      var lx = document.getElementById('location');
    typeIt("b");
}
else if (e.keyCode == '67') {
   //c
      var lx = document.getElementById('location');
    typeIt("c");
}
}

      



This should successfully convert the key code you press into a string letter that you can use in a larger function. It takes longer, but I found it to be very compatible with most browsers and keyboards (regardless of language). I used this code in a text editor project that will be distributed to friends in multiple countries, so I'm sure it will work. Note: The above function only includes the letters "A", "B" and "C".

0


source







All Articles