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.key
returns symbol or key name as string,e.code
returns key code as a string (similar to a key name ine.key
),e.keyCode
returns key code as a number - deprecated approach.
Note:
keydown
can be changed tokeyup
upkeypress
.
Practical example
In this example, we use the key
, code
and keyCode
properties to get information about pressed key.
Warnings:
key
andcode
were introduced around 2016 and is recommended to use,keyCode
is 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>