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:
xxxxxxxxxx
1
element.addEventListener('keydown', function(e) {
2
var message = 'key: ' + e.key + '\n' +
3
'code: ' + e.code + '\n' +
4
'keyCode (depricated): ' + e.keyCode + '\n\n';
5
console.log(message);
6
});
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
.
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.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div>Click here to get focus and press a key on the keyboard.</div>
5
<script>
6
7
document.addEventListener('keydown', function handleKeydown(e) {
8
var message = 'key: ' + e.key + '\n' +
9
'code: ' + e.code + '\n' +
10
'keyCode: ' + e.keyCode + '\n' +
11
'\n' +
12
'altKey: ' + e.altKey + '\n' +
13
'ctrlKey: ' + e.ctrlKey + '\n' +
14
'shiftKey: ' + e.shiftKey + '\n' +
15
'metaKey: ' + e.metaKey; // Windows key or Cmd key on macOS
16
console.clear();
17
console.log(message);
18
});
19
20
</script>
21
</body>
22
</html>