If you are reading this question post-2020 like me and trying to use it with TypeScript, you probably know that TypeScript will tell you that e.keyCode
or e.which
is deprecated!
So instead you can use e.key
which will give you the exact string of the key that is being pressed like it will give you Enter
for pressing the enter button or it will give you ctrl
for pressing the control btn, so hopefully you get the idea!
Also if you want to write a function to convert it to the old way of getting the key code you can use something like :
switch (theChar) {
case "Backspace":
return 8;
case "Tab":
return 9;
case "Enter":
return 13;
case "Alt":
return 18;
case "Escape":
return 27;
case "Delete":
return 127;
case "Minus":
return 45;
case "Plus":
return 43;
case "Equal":
return 61;
case "Delete":
return 127;
case "BracketRight":
return 93;
case "BracketLeft":
return 91;
case "Backslash":
return 92;
case "Slash":
return 47;
case "Semicolon":
return 59;
case "Colon":
return 58;
case "Comma":
return 44;
case "Period":
return 46;
case "Space":
return 32;
case "Quote":
return 34;
case "Backquote":
return 39;
//there are also "Numpad....." variants
case "Unidentified":
alert("handle the 'Unidentified' if you want to!");
}
There are many other possible character values here
but, AFAIK, there are no Unicode code points for them, such as:
switch (theKey) {
case "AltLeft":
case "CapsLock":
case "ControlRight":
case "Fn":
case "NumpadDecimal":
...
event.which
may output some number for them, but it is not consistent across browsers/machines and they may overlap with other code points.