How to convert a char to its keycode?
What do you mean by "keyCode"? Different browsers have different keyCode
values in keyup
and keydown
events which will not necessarily correspond to the ASCII code for the corresponding character. For alphanumeric keys, the keypress
event will give you the ASCII code in most browsers via the charCode
or which
properties. This page is useful.
Update September 2015
As pointed out by Jan in the comments, keyCode
will eventually be superseded by the superior key
property. However, there is not much browser support for this yet.
You can use the charCodeAt
function to achieve this.
Working example:
function showKeyCode () {
var character = document.getElementById("character").value.substring(0, 1);
var code = document.getElementById("character").value.charCodeAt(0);
var msg = "The Key Code for the \"" + character + "\" character is " + code + ".";
alert(msg);
}
<input type="text" id="character" size="15">
<input type="button" value="Show Key Code" onclick="showKeyCode();">
Here is a object with some keys and their corresponding keycodes:
{"0":48,"1":49,"2":50,"3":51,"4":52,"5":53,"6":54,"7":55,"8":56,"9":57,"d":68,"b":66,"a":65,"s":83,"i":73,"f":70,"k":75,"ß":219,"Dead":220,"+":187,"ü":186,"p":80,"o":79,"u":85,"z":90,"t":84,"r":82,"e":69,"w":87,"g":71,"h":72,"j":74,"l":76,"ö":192,"ä":222,"#":191,"y":89,"x":88,"c":67,"v":86,"n":78,"m":77,",":188,".":190,"-":189,"ArrowRight":39,"ArrowLeft":37,"ArrowUp":38,"ArrowDown":40,"PageDown":34,"Clear":12,"Home":36,"PageUp":33,"End":35,"Delete":46,"Insert":45,"Control":17,"AltGraph":18,"Meta":92,"Alt":18,"Shift":16,"CapsLock":20,"Tab":9,"Escape":27,"F1":112,"F2":113,";":188,":":190,"_":189,"'":191,"*":187,"Q":81,"W":87,"E":69,"R":82,"T":84,"Z":90,"S":83,"A":65,"D":68,"I":73,"U":85,"O":79,"Y":89,"X":88,"C":67,"F":70,"V":86,"G":71,"B":66,"H":72,"N":78,"J":74,"M":77,"K":75,"L":76,"P":80,"Ö":192,"Ä":222,"Ü":186,"!":49,"\"":50,"§":51,"$":52,"%":53,"&":54,"/":55,"(":56,")":57,"=":48,"?":219,"°":220}
if some keys are missing or are different for your browser, you can use the following function:
let a = {}
document.addEventListener("keydown", ({key, keyCode}) => a[key] = keyCode);
Just copy it to the console and smash your head on the keyboard. The result will be stored in a