Skip to content
Advertisement

Actual key assigned to JavaScript keyCode

I have setup an event listener:

editor.addEventListener('keydown', function(e) {
    if (e.shiftKey === false) {
        alert(String.charFromCode(e.keyCode).toLowerCase());
    }
    else {
        alert(String.charFromCode(e.keyCode));
    }
}, false);

When the user presses 2 along with shift, how do I know if I should output (@) or (“)? Each users’ character mapping is different per locale.

Advertisement

Answer

Use the keypress event instead. It will reliably (barring a few edge cases) detect the character typed.

There are a few browser oddities (such as some non-printable keys generating keypress events with key codes in the which property in some browsers) that prevent the following example from being 100% perfect which you can read about in great detail at the definitive page on JavaScript key events.

Example:

editor.addEventListener('keypress',
function(e)
{
    var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
    alert( String.charFromCode(charCode) );
},
false);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement