EN
JavaScript - detect when esc key was pressed
1 points
In this article, we would like to show you how to detect when the escape key was pressed using JavaScript.
Quick solution:
xxxxxxxxxx
1
element.addEventListener('keydown', function(e) {
2
if (e.key === 'Escape' || e.keyCode === 27) { // e.keyCode === 27 used for legacy
3
console.log('Escape key pressed');
4
}
5
});
In this example, we use the key
property that returns the value of the pressed key and then we compare it to the 'Escape'
to detect when the ESC
key was pressed.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div>Click here to set focus and press Escape key.</div>
5
<script>
6
7
document.addEventListener('keydown', function(e) {
8
if (e.key === 'Escape' || e.keyCode === 27) { // e.keyCode === 27 used for legacy
9
console.log('Escape key pressed');
10
}
11
});
12
13
</script>
14
</body>
15
</html>