79386759

Date: 2025-01-25 13:06:01
Score: 0.5
Natty:
Report link

While the keyCode attribute has been deprecated, the code attribute behaves similarly. The key attribute may help in the given usecase, as it will give you the character according to the keyboard layout.

In https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode the reason for the weired behavior is found. It is that browsers map non-symbol characters to some other values.

Specifically look at the table keyCode values of each browser's keydown event caused by printable keys in standard position (punctuations in US layout), where it is documented that a backslash can either map to code 220 or 221 depending on your browser, keyboard layout and operating system.

As this behavior seems exceedingly confusing, i would suggest just using the key attribute.

    function test(e) {
       e = e || window.e;
       var keyCode = e.which || e.code;
       
       alert(keyCode +' -> '+ e.key);
    }

If you are using a US-keyboard layout, pressing backslash should produce "220 -> \"

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Unregistered user (0.5):
  • Low reputation (1):
Posted by: Simon