How to Detect Which Key is Pressed using JavaScript?

To detect which key is pressed by the user, you can use the event.key property. The event.key property returns the name of the pressed key as a string such as ‘Enter’, ‘Backspace’, ‘a’, ‘b’, ‘c’, etc.

Let’s say we have a text input box in our HTML with an id myInput:

<input type="text" id="myInput" placeholder="Type something">

Now, we want to detect which key is pressed by the user into this input box.

To achieve that we have to add an event listener to this input box to listen to the keyup event and get the value of the key pressed by the user using event.key property:

const input = document.getElementById('myInput');

input.addEventListener('keyup', function(event){
    
    alert('You have pressed: '+ event.key);  // Returns key value
    
});

If you want to get the key code of the pressed key, you can use the event.which property. The event.which property returns the Unicode value of the pressed key such as 13 for the Enter key, 32 for the Space key, and so on:

const input = document.getElementById('myInput');

input.addEventListener('keyup', function(event){
    
    alert('Key code of the pressed key is: '+ event.which); // Returns key code
    
});

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.