EN
JavaScript - detect when right arrow key was pressed
0 points
In this article, we would like to show you how to detect when the right 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 (39
) of the right arrow key instead of a string (ArrowRight
).
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 right arrow.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div>Click here to get focus and press right arrow key.</div>
5
<script>
6
7
var MAPPING = {
8
39: 'ArrowRight',
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 === 'ArrowRight') {
18
console.log('Arrow right 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 right arrow.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div>Click here to get focus and press right arrow key.</div>
5
<script>
6
7
var MAPPING = {
8
39: 'ArrowRight',
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 === 'ArrowRight') {
18
console.log('Arrow right pressed.');
19
}
20
});
21
22
</script>
23
</body>
24
</html>