Javascript key is not called when command and other are pressed

This is a problem only with the Mac; I tried this in windows and it works great.

I have a script that saves which keys are pressed on keydown , and removes them on keyup .

 $(function(){ var keys = []; $(document).keydown(function(event) { keys[event.which] = true; }); $(document).keyup(function(event) { delete keys[event.which]; console.log(keys); }); }); 

All I'm doing right now is console logging left over from keyup, which should be nothing. This works as expected when you press any number of keys simultaneously.

HOWEVER, when you press command and any other key, the other key is NOT released! Thus, console.log will show that the key will be true . This will remain true until you press this key.

This only happens on a Mac, and it only happens when you press one of the Command keys. Here is a very simple plunker with the above example.

Any ideas?

+5
source share
2 answers

The Mac changes your key whenever you press Command , and so the normal keyup event never fires.

C = command key and K = non-command key

When you press C and K , they are registered normally. While both are simultaneously pressed, the Mac grabs K and changes it. When modifying K Mac somehow makes the K keyup event not fire as intended. C keyup works as expected.

Since K keyup never fires, it will not correctly remove the corresponding element from keys . Later, when you press K without C , the keydown event overwrites the existing keydown in keys . And when K keyup works correctly, it works as expected.


In addition to all the normal keys used to enter ASCII characters, keyboards usually have many special-purpose keys that do other things. They do not necessarily generate the same events as regular ones and they show less consistency between browsers.

JavaScript Madness: Keyboard Events . A potentially useful article for all key related issues.

+2
source

I cannot fix this problem with a Mac, but here is my way around it.

This answer will help you if you are trying to use the keyboard keys behavior when the user presses CMD + S to save or something like that. This answer does not apply to people who can create a game or something where their key keyboard states should be known in every launch frame. Sorry!

In the KeyboardEvent returned by keydown, you can do the following

 $(document).keydown(function(keyboardEvent) { if (keyboardEvent.metaKey){ // on Mac, CMD is down ...or Meta key is down on pc console.log(keyboardEvent.meta + " & command key are down") switch (keyboardEvent.which) { ... } } }); 

If your keyboard shortcut overlaps with the browser, you need to disable the keyboard event distribution,

 keyboardEvent.preventDefault() 

I hope this helps people who need Mac compatible keyboard functionality!

+1
source

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


All Articles