Some chords do not work with onkeydown (JavaScript)

Some keyboards β€œchords” (simultaneous keystrokes) will not be correctly registered in the browser (tested by Chrome and Firefox). For example, using the code below, try the following:

1) press the "e" key (it will record "key 69")

2) while holding "e", press "]" (it will record "key 221")

3) while still holding β€œe” and β€œ]”, press β€œi” (this will not work!)

4) however, if you go down to β€œi” and press β€œo” instead, it will successfully register β€œkey 79”.

document.onkeydown = function(event){ var key = event.keyCode; console.log("key", key); }; 

Can someone explain what is going on here and if there is some workaround? For context, I am developing a QWERTY based music application, and I would like to play all my chords.

I know that keyCode out of date, maybe this behavior is one of the reasons?

What is the correct approach to this problem?

Demo here: https://jsfiddle.net/nt0ad2ap/

+5
source share
2 answers

I am sure that 99.9% depends on the keyboard hardware itself. I tried to do e + ] + i on the keyboard connected to the laptop, but it does not work, but when I press e + ] on this keyboard and then press i on the laptop, then it works. The keyboard is usually not created to register several keys at once (except shift , ctrl and alt ), because this is usually not required. There is a special keyboard, built mainly for games, which can register several keys at once. Try googling "anti-ghosting keyboard". Here is a quora question about this topic. I have a keyboard that allows you to register 13 keys pressed at home. I will check if the code works with this keyboard after a few hours when I get home.

UPDATE:

Works great on the best keyboard. This is a hardware problem.

+2
source

221 is keyCode for ] , and 79 is keyCode for o , so you do not get a code representing a combination of two or more keys pressed at the same time. So:

  • press the "e" key (it will record "key 69") - it's OK
  • while holding down the "e" button, press the "]" (it will record "key 221"). You get the code (221) for the last key pressed ]
  • still holding "e" and "]", press "i" (this is not log!) - I cannot reproduce this script, I get code 73, which is the code for i
  • however, if you go down to "i" and press "o", it will successfully register "key 79". - You get the code for the last click clicked o

If you need to combine keys in JavaScript, you should consider altKey , ctrlKey , shiftKey , metaKey

Here is an old example that might prove useful. Hope this helps.

0
source

Source: https://habr.com/ru/post/1274348/


All Articles