Search code examples
javascriptjquerykeypressmeta-key

jQuery not detecting modifiers on keyup


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

Solution

  • 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