EN
JavaScript - get keyboard key property value
3
points
In this article, we would like to show you how to get keyboard key code value using JavaScript.
Quick solution:
element.addEventListener('keydown', function(e) {
var message = 'key: ' + e.key + '\n' +
'code: ' + e.code + '\n' +
'keyCode (depricated): ' + e.keyCode + '\n\n';
console.log(message);
});
Where:
e.keyreturns symbol or key name as string,e.codereturns key code as a string (similar to a key name ine.key),e.keyCodereturns key code as a number - deprecated approach.
Note:
keydowncan be changed tokeyupupkeypress.
Practical example
In this example, we use the key, code and keyCode properties to get information about pressed key.
Warnings:
keyandcodewere introduced around 2016 and is recommended to use,keyCodeis marked as depricated but is still used as legacy.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<div>Click here to get focus and press a key on the keyboard.</div>
<script>
document.addEventListener('keydown', function handleKeydown(e) {
var message = 'key: ' + e.key + '\n' +
'code: ' + e.code + '\n' +
'keyCode: ' + e.keyCode + '\n' +
'\n' +
'altKey: ' + e.altKey + '\n' +
'ctrlKey: ' + e.ctrlKey + '\n' +
'shiftKey: ' + e.shiftKey + '\n' +
'metaKey: ' + e.metaKey; // Windows key or Cmd key on macOS
console.clear();
console.log(message);
});
</script>
</body>
</html>