Categories
JavaScript Answers

How to Find Out What Character Key is Pressed with JavaScript?

Spread the love

We can find out which character key is pressed with the e.which property and the String.fromCharCode method.

For instance, if we have the following input:

<input type="text"  />

Then we can listen to the keypress event and check which key is pressed by writing:

const input = document.querySelector('input')  
input.addEventListener('keypress', (e) => {  
  console.log(String.fromCharCode(e.which));  
})

We call String.fromCharCode with e.which in the keypress event handler callback to get the character of the key that’s pressed.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *