fish potato
fish potato

Reputation: 5629

keycode and fromCharCode in javascript

I wrote the following code (using jQuery) to show the pressed key.

$(window).keydown(function(e){
  $("div").text("Key:" + String.fromCharCode(e.keyCode).toLowerCase());
  return false;
});

This code works in normal alphabet characters (q,w,e,r...). But when I press non alphabet keys (like ']'), an incorrect character is shown.

ex: ',' -> ¼, ']' -> ý

What's wrong with my code?

Upvotes: 1

Views: 6581

Answers (1)

Rob W
Rob W

Reputation: 348992

Use the keypress event and e.which property.

jQuery normalizes the keycodes, and stores the variable in event.which. The keypress event's which property is the only reliable value for String.fromCharCode.

The event.keyCode property may not be equal to the event.charCode or event.which properties.

For non-printable characters, event.which has a value of zero, contrary to event.keyCode. That's why you're seeing weird characters.

$(window).keypress(function(e) {
    var charCode = e.which;
    if (!charCode) { // <-- charCode === 0
        return;// return false, optionally
    }
    $("div").text("Key:" + String.fromCharCode(charCode).toLowerCase());
    return false; // Or e.preventDefault(); and/or e.stopPropagation()
}).keyup(function(e) {
    // Key is lifted, do something
});

Upvotes: 8

Related Questions