-2

this is the js code:

document.addEventListener('keyup', function (e) {
    e.preventDefault();
    if (e.keyCode === 191) {
        document.getElementById('search-input').focus()
    }
})

but in visual studio code says: keyCode is deprecated. What should this code be replaced with? Is there any need to do this at all?

  • 2
    check MDN [KeyboardEvent.keyCode](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode) – sohaieb azaiez Aug 25 '21 at 13:46
  • 1
    see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode and use if (e.code=== 191) { – Divek John Aug 25 '21 at 13:47
  • Is that answer your question ? https://stackoverflow.com/questions/35394937/keyboardevent-keycode-deprecated-what-does-this-mean-in-practice – JS_INF Aug 25 '21 at 13:48
  • Does this answer your question? [event.keyCode alternative](https://stackoverflow.com/questions/29250534/event-keycode-alternative) – Wazner Aug 25 '21 at 13:51

3 Answers3

3

Replace it with e.key === 'Enter' for example or e.code === 'Enter'. You can find more information about it here and here.

PRSHL
  • 1,359
  • 1
  • 11
  • 30
0

Use e.key. It's way easier to use, and working in every browser:

document.addEventListener('keyup', function (e) {
    e.preventDefault();
    if (e.key == '/') {
        document.getElementById('search-input').focus()
    }
});
Jake
  • 97
  • 1
  • 9
0

The MDN documentation states the following:

You should avoid using this (keyCode) if possible; it's been deprecated for some time. Instead, you should use KeyboardEvent.code, if it's implemented. Unfortunately, some browsers still don't have it, so you'll have to be careful to make sure you use one which is supported on all target browsers.

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

If you need to support older browsers (like Internet Explorer) you may want to use feature detection to use the correct one.

if (event.code !== undefined) {
    // Handle the event with KeyboardEvent.key
}
else if (event.keyCode !== undefined) {
    // Handle the event with KeyboardEvent.keyCode
}
Wazner
  • 2,962
  • 1
  • 18
  • 24