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
2
on the keyboard - Capture the event.
event.keyCode
is 50. - The UTF character 50 is
2
(DIGIT TWO)
but:
- Type
[
on the keyboard - Capture the event.
event.keyCode
is 219. - The UTF character 219 is
Û
(LATIN CAPITAL LETTER U WITH CIRCUMFLEX) - The charcode I wish the event contained is
91
which corresponds to LEFT SQUARE BRACKET.
How do I convert Javascript keyCodes (e.g. 219
) into UTF-8 charCodes (e.g. 91
)?