To detect whether the user has pressed enter key or not, you can use the event.keyCode
or event.which
property. Both properties return the Unicode character code of the key that is pressed by the user.
If the code of the pressed key is 13 then the user has pressed the enter key otherwise not. That’s it.
Let’s say we have a text input box in our HTML file with some id e.g. myInput:
<input type="text" id="myInput" placeholder="Type something">
Now, you have to add an EventListener to this input box on the keyup
event to detect the key press event. If the key code of the pressed key is 13 then it’s an enter key otherwise not:
let input = document.getElementById('myInput'); input.addEventListener('keyup', function(event){ if(event.keyCode===13){ alert('You have pressed an enter key'); } });
The event.keyCode
property is now deprecated. So, you should use event.which
instead. It also returns the Unicode of the pressed key:
let input = document.getElementById('myInput'); input.addEventListener('keyup', function(event){ if(event.which===13){ alert('You have pressed an enter key'); } });
Method 2 – Use event.key
You could also use the event.key
property to check if the pressed key is the enter key. The event.key
property returns the name of the pressed key:
let input = document.getElementById('myInput'); input.addEventListener('keyup', function(event){ if(event.key=='Enter'){ alert('You have pressed an enter key'); } });