2

I am tyring to read the input characters on keydown event and try to process them. When I am triing to convert them into character using "String.fromCharCode(key);" Its always giving me the capital letters.

Upadte: Strangely the code works if I listen for "keypress" event. What is the reason for this. Could some one please explain this behavoir.

The sample code is given below:

var inp = document.getElementById("ti");

inp.addEventListener("keydown", onKeyDown);

function onKeyDown(e) {
    if (window.event) {
        var key = window.event.keyCode;
    } else {
        var key = e.keyCode;
    }
    document.getElementById("output").innerHTML +=  String.fromCharCode(key);
}

What is the best practice to read the character on keydown event

Fiddle Demo

  • 1
    http://jsfiddle.net/zZtW9/1/ – elclanrs Feb 12 '14 at 11:05
  • 1
    possible duplicate of [onKeyPress Vs. onKeyUp and onKeyDown](http://stackoverflow.com/questions/3396754/onkeypress-vs-onkeyup-and-onkeydown) – elclanrs Feb 12 '14 at 11:08
  • @elclanrs Thanks, what is the reason for this. Could you please explain this behavoir. What is the best practice when handling keyboard events –  Feb 12 '14 at 11:10
  • http://stackoverflow.com/questions/12568494/keyup-event-always-return-uppercase-letter – Nicolae Olariu Feb 12 '14 at 11:14
  • `keypress` will give you correct char code, that's the main difference. Use `keydown` and `keyup` for special characters. But you could just assign the value of the input to the div http://jsfiddle.net/zZtW9/5/ – elclanrs Feb 12 '14 at 11:15

3 Answers3

0

Try keypress instead of keydown

 inp.addEventListener("keypress", onKeyDown);

In theory, the keydown and keyup events represent keys being pressed or released, while the keypress event represents a character being typed. The implementation of the theory is not same in all browsers.

DEMO

Amit
  • 15,217
  • 8
  • 46
  • 68
0

Guess you only need to change the EventListener to keypress

var inp = document.getElementById("ti");

inp.addEventListener("keypress", onKeyDown);

function onKeyDown(e) {
    if (window.event) {
        var key = window.event.keyCode;
    } else {
        var key = e.keyCode;
    }
    document.getElementById("output").innerHTML += String.fromCharCode(key);
}

Fiddle: http://jsfiddle.net/zZtW9/4/

Take a look here,you can note learn the differences from here : http://www.w3resource.com/html/attributes/HTML-event-attributes-completed.php

EDIT: For your doubt,check this : keyup event always return uppercase letter

Community
  • 1
  • 1
Nevin Madhukar K
  • 3,031
  • 2
  • 25
  • 52
0

I wrote a module called keysight that translates keypress, keydown, and keyup events into characters and keys respectively.

Example:

 inp.addEventListener("keydown", function(event) {
    var character = keysight(event).char
    document.getElementById("output").innerHTML +=  character
 })
B T
  • 57,525
  • 34
  • 189
  • 207