EN
JavaScript - detect when arrow key was pressed
6 points
In this article, we would like to show you how to detect when the arrow key was pressed using JavaScript.
The main idea of how to detect the arrow key is to check the key code when the key event occurred.
Key codes:
Key name | Key code ( event.key , event.code ) | Deprecated key code ( event.keyCode ) |
---|---|---|
Left arrow | ArrowLeft | 37 |
Up arrow | ArrowUp | 38 |
Right arrow | ArrowRight | 39 |
Down arrow | ArrowDown | 40 |
In the below example, we use some legacy function that lets to get key code. The main reason why that approach was used, is the time when event.key
and key.code
were introduced in the major web browsers (around 2016-2017). To see the result, each arrows key is handled and displayed a message in the console.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div>Click here to get focus and press arrow keys.</div>
5
<script>
6
7
var MAPPING = {
8
37: 'ArrowLeft',
9
38: 'ArrowUp',
10
39: 'ArrowRight',
11
40: 'ArrowDown',
12
};
13
14
function getKey(event) {
15
return event.key || MAPPING[event.keyCode]; // with legacy support
16
}
17
18
document.addEventListener('keydown', function(event) {
19
var key = getKey(event);
20
switch (key) {
21
case 'ArrowLeft':
22
console.log('Arrow left pressed.');
23
break;
24
case 'ArrowUp':
25
console.log('Arrow up pressed.');
26
break;
27
case 'ArrowRight':
28
console.log('Arrow right pressed.');
29
break;
30
case 'ArrowDown':
31
console.log('Arrow down pressed.');
32
break;
33
}
34
});
35
36
</script>
37
</body>
38
</html>
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div>Click here to get focus and press arrow keys.</div>
5
<script>
6
7
var MAPPING = {
8
37: 'ArrowLeft',
9
38: 'ArrowUp',
10
39: 'ArrowRight',
11
40: 'ArrowDown',
12
};
13
14
function getCode(event) {
15
return event.code || MAPPING[event.keyCode]; // with legacy support
16
}
17
18
document.addEventListener('keydown', function(event) {
19
var code = getCode(event);
20
switch (code) {
21
case 'ArrowLeft':
22
console.log('Arrow left pressed.');
23
break;
24
case 'ArrowUp':
25
console.log('Arrow up pressed.');
26
break;
27
case 'ArrowRight':
28
console.log('Arrow right pressed.');
29
break;
30
case 'ArrowDown':
31
console.log('Arrow down pressed.');
32
break;
33
}
34
});
35
36
</script>
37
</body>
38
</html>