Use event.keyCode to get the keycode of the pressed keyboard key in JavaScript. The keyCode property returns the Unicode character code of the key that triggered the onkeypress event.
JavaScript get keycode Example
HTML example JavaScript gets keycode from char pressed by the user. When the user presses the button it will show output into a console.
It’s the simplest way to detect keypresses in JavaScript.
<!DOCTYPE html>
<html>
<body>
<script>
document.addEventListener('keypress', function(e) {
console.log("Key: " + e.code + ", Code: " + e.charCode)
});
</script>
</body>
</html>
Output:
Vanilla JavaScript + Alert:
document.addEventListener('keypress', function(e) {
alert("Key: " + e.code + ", Code: " + e.charCode)
});
Do comment if you have any doubts and suggestions on this JS Keycode topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version