Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyboardEvent.keyCode deprecated. What does this mean in practice?

According to MDN, we should most definitely not be using the .keyCode property. It is deprecated:

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

On W3 school, this fact is played down and there is only a side note saying that .keyCode is provided for compatibility only and that the latest version of the DOM Events Specification recommend using the .key property instead.

The problem is that .key is not supported by browsers, so what should we using? Is there something I'm missing?

like image 841
Jason210 Avatar asked Sep 27 '22 19:09

Jason210


People also ask

What is deprecated keyCode?

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes.

Is keyCode deprecated in JavaScript?

KeyCode was deprecated because in practice it was “inconsistent across platforms and even the same implementation on different operating systems or using different localizations.” The new recommendation is to use key or code .


2 Answers

For instance if you want to detect whether the "Enter"-key was clicked or not:

Instead of

event.keyCode === 13

Do it like

event.key === 'Enter'
like image 157
Thomas Gotwig Avatar answered Oct 23 '22 00:10

Thomas Gotwig


You have three ways to handle it, as it's written on the link you shared.

if (event.key !== undefined) {

} else if (event.keyIdentifier !== undefined) {

} else if (event.keyCode !== undefined) {

}

you should contemplate them, that's the right way if you want cross browser support.

It could be easier if you implement something like this.

var dispatchForCode = function(event, callback) {
  var code;

  if (event.key !== undefined) {
    code = event.key;
  } else if (event.keyIdentifier !== undefined) {
    code = event.keyIdentifier;
  } else if (event.keyCode !== undefined) {
    code = event.keyCode;
  }

  callback(code);
};
like image 70
Miguel Lattuada Avatar answered Oct 23 '22 02:10

Miguel Lattuada