Reputation: 326
How can one determine the Unicode of the key pressed in javascript?
I googled on this and most of the results only answer as to how to find the keyCode. Any help would be greatly appreciated.
Upvotes: 4
Views: 4925
Reputation: 201628
In theory, as per DOM3 Events, you should use the key
property of an event object. In practice, it doesn’t work, except in sufficiently new versions of IE.
The practical approach is to use the which
property or the charCode
property, even though the DOM3 Events draft frowns upon them:
Browser support for keyboards has traditionally relied on three ad-hoc attributes,
keyCode
,charCode
, andwhich
.All three of these attributes return a numerical code that represents some aspect of the key pressed:
keyCode
is an index of the key itself.charCode
is the ASCII value of the character keys.which
is the character value where available and otherwise the key index. The values for these attributes, and the availability of the attribute, is inconsistent across platforms, keyboard languages and layouts, user agents, versions, and even event types.
In reality, charCode
returns the Unicode value (code number).
The following simple code can be used to test the functionality (it just echoes the character number in an element on the page):
<style>
#o { border: solid black 1px; }
</style>
<input id=i>
<div id=o></div>
<script>
document.getElementById('i').onkeypress = function (e) {
var ev = e || window.event;
document.getElementById('o').innerHTML +=
ev.charCode + ' ';
}
</script>
This seems to work in modern browsers, including IE 9 and newer. For older browsers, you may need to try to do something with keyCode
based on a guess of the keyboard mapping.
Upvotes: 2