How to get LOCALIZED character on keypress?

Honza Kuchař picture Honza Kuchař · Mar 24, 2011 · Viewed 10.1k times · Source

I need to get localized character on keypress event. For example: on a Czech keyboard I need to get ř not 5 character (key code 53) (see Czech keyboard layout). Is there any other way to get character and to not use text input and reading value? By other words is there any way how to get character from event object respecting current user keyboard layout?


(Added sample code)

<html>
<body>
<script language="JavaScript">
function onLoad() {
    console.log(document.getElementById("test"));
    document.getElementById("test").onkeydown = function(event) {
                console.log("Code: "+event.keyCode+"; Key: "+String.fromCharCode(event.keyCode));
        }
}
</script>
<body onLoad="onLoad();">
    <input id="test">
</body>
</html>

(Example online)

When you try this code, and you press ř-key you will see in Firebug console "Code: 53; Key: 5". And I need to get "ř" not "5".

I think that this "problem" appears on all non-English keyboards.

Answer

Tim Down picture Tim Down · Mar 24, 2011

Using the keypress event will give you the character typed, regardless of keyboard layout.

document.onkeypress = function(evt) {
    evt = evt || window.event;
    var charCode = evt.which || evt.keyCode;
    var charTyped = String.fromCharCode(charCode);
    alert("Character typed: " + charTyped);
};

Here's my usual link to Jan Wolter's excellent page documenting JavaScript key handling: http://unixpapa.com/js/key.html