In a Javascript keyboard event, a code is given for the key pressed, however, it is not an ASCII or UTF-8 character code, rather, it is a code for the keyboard key. Sometimes the keyCodes happen to match up with ASCII/UTF-8 codes, sometimes they do not.
Is there a way, given a Javascript key code, (accessed via e.keyCode or e.which) to get the corresponding ASCII or UTF-8 charcode?
Here's a working JSFiddle to demonstrate what I mean, or run the snippet below.
document.addEventListener("keyup", function(e) {
document.querySelector(".key").innerHTML = e.key;
document.querySelector(".keyCode").innerHTML = e.keyCode;
document.querySelector(".UTF").innerHTML = String.fromCharCode(event.keyCode);
});
code {
background-color: #e2aec8ab;
border: solid 1px gray;
border-radius: 3px;
padding: 0 .5em;
min-height: 1em;
min-width: .2em;
margin: 0 .1em;
}
.output {
margin: 2em;
border: solid 1px lightgray;
border-radius: 3px;
background-color: rgba(200, 250, 230, .3);
padding: 1em;
}
Type here. Try some alpha letters as well as special keys like <code>`</code>
<code>-</code>
<code>=</code>
<code>[</code>
<code>]</code>
<code>[ENTER]</code>
<code>;</code>
<code>'</code>
<div class="output">
You typed <code class="key"></code> which is Javascript <b></b>keyCode</b> <code class="keyCode"></code>, in UTF that would be <code class="UTF"></code>
</div>
Two examples:
- Type
2on the keyboard - Capture the event.
event.keyCodeis 50. - The UTF character 50 is
2(DIGIT TWO)
but:
- Type
[on the keyboard - Capture the event.
event.keyCodeis 219. - The UTF character 219 is
Û(LATIN CAPITAL LETTER U WITH CIRCUMFLEX) - The charcode I wish the event contained is
91which corresponds to LEFT SQUARE BRACKET.
How do I convert Javascript keyCodes (e.g. 219) into UTF-8 charCodes (e.g. 91)?
I just want to say, this question became a fun learning adventure. But....
You're using deprecated APIs.
As it turns out KeyboardEvent.keyCode has been deprecated for a while. Because it uses the decimal version of ASCII. The correct code to use is actually
event.Code. But that's not what you're after.To get the ascii number, you can just use
event.key.charCodeAt()This does have some flaws as it will reportSwhen you hit shift. But you can useevent.locationto figure out if the key is a special control key. Zero is standard keys and 1-3 are special locations (I think).