Detect whether a user has pressed Enter with JavaScript/jQuery
This post will discuss how to detect whether the user has pressed Enter in JavaScript and jQuery.
The idea is to bind an event handler to the keydown or keyup JavaScript event and use that handler to check for the Enter key. There are several properties in the KeyboardEvent object, which returns the value of the key pressed by the user.
1. Using jQuery
To watch for the keyboard key input, you can use the event.which property in jQuery. The following example binds an event handler to the keyup event using the .keyup(handler) method and then matches the keyCode value against number 13 to check if the Enter key is pressed.
JS
|
1 2 3 4 5 |
$(document).keyup(function(event) { if (event.which === 13) { alert('Enter is pressed!'); } }); |
HTML
|
1 2 3 |
<p> Press Enter key! </p> |
2. Using JavaScript
In plain JavaScript, you can use the EventTarget.addEventListener() method to listen for keyup event. When it occurs, check the keyCode‘s value to see if an Enter key is pressed.
JS
|
1 2 3 4 5 |
document.addEventListener("keyup", function(event) { if (event.keyCode === 13) { alert('Enter is pressed!'); } }); |
HTML
|
1 2 3 |
<p> Press Enter key! </p> |
Note that KeyboardEvent.keyCode attribute is deprecated, you should use the KeyboardEvent.code instead. It is set to the string Enter whenever the Enter key is pressed.
JS
|
1 2 3 4 5 |
document.addEventListener("keyup", function(event) { if (event.code === 'Enter') { alert('Enter is pressed!'); } }); |
HTML
|
1 2 3 |
<p> Press Enter key! </p> |
You can also use the KeyboardEvent.key attribute similarly.
JS
|
1 2 3 4 5 |
document.addEventListener("keyup", function(event) { if (event.key === 'Enter') { alert('Enter is pressed!'); } }); |
HTML
|
1 2 3 |
<p> Press Enter key! </p> |
That’s all about detecting whether a user has pressed Enter in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)