EN
JavaScript - detect when left arrow key was pressed
0 points
In this article, we would like to show you how to detect when the left arrow key was pressed using JavaScript.
In the below solutions, we use some legacy functions 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).
Both of the examples below provide the legacy support for the keyCode
property which represents an integer value (37
) of the left arrow key instead of a string (ArrowLeft
).
In this example, we use event.key
to get the value of the key pressed by the user and then check if it's a left arrow.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div>Click here to get focus and press left arrow key.</div>
5
<script>
6
7
var MAPPING = {
8
37: 'ArrowLeft',
9
};
10
11
function getKey(event) {
12
return event.key || MAPPING[event.keyCode]; // with legacy support
13
}
14
15
document.addEventListener('keydown', function(event) {
16
var key = getKey(event);
17
if (key === 'ArrowLeft') {
18
console.log('Arrow left pressed.');
19
}
20
});
21
22
</script>
23
</body>
24
</html>
In this example, we use event.code
to get the value of the key pressed by the user and then check if it's a left arrow.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div>Click here to get focus and press left arrow key.</div>
5
<script>
6
7
var MAPPING = {
8
37: 'ArrowLeft',
9
};
10
11
function getCode(event) {
12
return event.code || MAPPING[event.keyCode]; // with legacy support
13
}
14
15
document.addEventListener('keydown', function(event) {
16
var code = getCode(event);
17
if (code === 'ArrowLeft') {
18
console.log('Arrow left pressed.');
19
}
20
});
21
22
</script>
23
</body>
24
</html>