EN
JavaScript - detect when enter key was pressed
3 points
In this article, we would like to show you how to detect when the Enter
key was pressed using JavaScript.
Quick solution:
xxxxxxxxxx
1
element.addEventListener('keydown', function(e) {
2
if (e.key === 'Enter' || e.keyCode === 13) { // e.keyCode === 13 used for legacy
3
console.log('Enter key pressed');
4
}
5
});
Note:
element
object can be replaced with other objects like some node,window
,document
, etc.
In this example, we present how to detect when Enter
key was pressed using key
property of the KeyboardEvent object.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div>Click here to set focus and press Enter key.</div>
5
<script>
6
7
window.addEventListener('keydown', function(e) {
8
if (e.key === 'Enter' || e.keyCode === 13) { // e.keyCode === 13 used for legacy
9
console.log('Enter key pressed');
10
}
11
});
12
13
</script>
14
</body>
15
</html>