How to capture Enter key press in JavaScript
Today we will show you how to capture Enter key press in JavaScript. Here we will detect whether a user has hit the Enter key with JavaScript/jQuery.
Checkout more articles on JavaScript
Capture Enter key press in JavaScript
1. Using jQuery
The event.which
property in jQuery can be used to keep an eye on keyboard key input. The .keydown
(handler) function is used to bind an event handler to the keydown event, and then the keyCode
value is compared to number 13
to see if the Enter key is pressed.
1 2 3 4 5 | $(document).keydown(function(event) { if (event.which === 13) { alert('Enter key is pressed!'); } }); |
We’ve bound the .keydown
event on document
in the preceding code. You may also use the input
field to bind it.
2. Using JavaScript
To listen for keydown events in simple JavaScript, use the addEventListener()
function. When this happens, look at the value of the keyCode
variable to determine if an Enter key has been hit.
1 2 3 4 5 | document.addEventListener("keydown", function(event) { if (event.keyCode === 13) { alert('Enter key is pressed!'); } }); |
The keyCode
attribute has been deprecated; instead, use the code
attribute. When the Enter key is pushed, it is set to the string Enter
.
1 2 3 4 5 | document.addEventListener("keydown", function(event) { if (event.code === 'Enter') { alert('Enter key is pressed!'); } }); |
Similarly, you may use the event.key
attribute.
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂