key vs keyCode vs which
Written byPhuoc Nguyen
Created
16 Jun, 2020
Category
DOM
`key`
, `keyCode`
and `which`
can be used to determine which key is pressed. Following is a sample code that handles the `keyPress`
event of a text box.It checks if user presses the Enter key whose key code is 13:
js
textBoxElement.addEventListener('keydown', function (e) {
if (e.keyCode === 13) {
// Do something ...
}
});
#Difference
According to MDN documentations, both keyCode and which are deprecated and will be removed from the Web standards.
Apart from that, both properties are supported differently by browsers. Some browsers use
`keyCode`
, other use `which`
.It's common to see how they are normalized as following:
js
const key = 'which' in e ? e.which : e.keyCode;
// Or
const key = e.which || e.keyCode || 0;
#Good practice
It's recommended to use the key property.
The sample code above can be rewritten as
js
if (e.key === 'Enter') {
// Enter is pressed
}
Questions? 🙋
Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Recent posts ⚡
Newsletter 🔔
If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn