1

When I run the following code and press the command key on my Mac (using Chrome), metaKey is set for keydown but not for keyup. Am I doing something wrong? I'm just trying to track the meta key being pressed so I can use it inside my JavaScript - if there's a better way please let me know :-)

   var metaPressed = false;
   $(document).keydown(function(e) {
     console.log('keydown ' + e.keyCode);
     if (e.metaKey || e.ctrlKey) {
       console.log('meta pressed');
       metaPressed = true;
     }
   });
   $(document).keyup(function(e) {
     console.log('keyup ' + e.keyCode);
     if (e.metaKey || e.ctrlKey) {
       console.log('meta unpressed');
       metaPressed = false;
     }
   });

Here's the console output for the relevant keys

// Pressing cmd
keydown 91
meta pressed
keyup 91

// Pressing control 
keydown 17
meta pressed 
keyup 17

// Pressing non-meta like spacebar
keydown 32
keyup 32
AstroCB
  • 12,337
  • 20
  • 57
  • 73
Hamy
  • 20,662
  • 15
  • 74
  • 102
  • 3
    Not sure I get it, isn't that just as expected, the keyup event fires when the button is released so e.metaKey will be false at that point even if the keyup event fires with the correct keyCode ? – adeneo Sep 28 '14 at 19:23

3 Answers3

1

I get it now, I was misunderstanding how jQuery handles modifier keys. Thanks to @adeneo for the prompt that got me thinking correctly.

Also, if you press keys while holding a meta character, e.g. press M-x, jQuery doesn't send the keyup for 'x' until it the 'M' is also released. So you don't have to worry about things like "meta down, x down, x up, meta up" happening

Hamy
  • 20,662
  • 15
  • 74
  • 102
0

You won't be able to retrieve that information from the keyup. I would recommend to use this (e.keyCode === 17 || e.keyCode === 91) as test case (which are CTRL and META respectively)

tfrascaroli
  • 1,178
  • 1
  • 14
  • 26
  • These keyCodes are browser-dependent. – Damien Oct 02 '15 at 18:01
  • @Damien http://unixpapa.com/js/key.html. If you scroll down you will see that the CTRL key is consistent across browsers. Windows Meta is not correctly supported in Opera, but its browser usage share is neglectible anyway (also not the OP's use case) – tfrascaroli Oct 05 '15 at 08:28
  • The codes for the command key are different for each browser on MacOS, and Safari is using 2 codes. See http://stackoverflow.com/a/3922353/438970 . – Damien Oct 13 '15 at 15:12
0

I'm using React and noticing the same issue. e.metaKey works on keydown but not keyup. e.keyCode is 93 for both, however.

kmoser
  • 8,780
  • 3
  • 24
  • 40
ladder
  • 189
  • 2
  • 9