Search code examples
javascriptjquerydom-eventskeyevent

When CMD key is kept pressed, keyup is not triggered for any other key


I am developing an application where I need to do some post-processing when the user presses CMD+LEFT on a particular text-box. I need to do this after the browser's default functionality (i.e. after it takes the caret to first position in current physical line).

The problem is keyup is not being triggered for the LEFT key (or any key for that matter) as long as the CMD key is down.

I tried this with CTRL and SHIFT keys and found that keyup gets triggered as expected for the secondary key. So if you do CTRL+LEFT and then release LEFT and then release CTRL, you get four events in total, 2 keydowns and 2 keyups. For the CMD key however, we get 2 keydowns, but only one keyup event (the one for CMD key itself when we release it in the end).

I tried this with SHIFT key and found that keyup gets triggered as expected for the secondary key. So if you do SHIFT+LEFT and then release LEFT and then release SHIFT, you get 4 events in total, 2 keydowns and 2 keyups. For the CMD key however, we get 2 keydowns, but only one keyup event (the one for CMD key itself when we release it in the end).

What could it be? Is there any way I can get keyup triggered for the LEFT key (or any key) when CMD is down?

I'm trying this with the latest Google Chrome on OSX 10.9.5. The behaviour is exactly the same on Firefox too. So this isn't a Chrome issue.

Demo: http://jsfiddle.net/techfoobar/xu0o11nh/4/

Essentially:

$('#mytextbox')

    // this gets correctly triggered for the meta key as well as the secondary key
    // when you press CMD and LEFT in sequence, you get two lines in the console one for 
    // the CMD key and one for the LEFT key
    .keydown(function(_e) {
        console.log('Keydown: ' + _e.keyCode);
    })

    // however, if I release the LEFT key (while keeping the CMD key down)
    // this does NOT get triggered for the LEFT key
    .keyup(function(_e) {
        console.log('Keyup: ' + _e.keyCode);
    });

Solution

  • This is known behavior with the meta key, and there is unfortunately no known workaround.

    For your case, you may consider implementing the default browser behavior yourself (how to do that), then implement the custom behavior you need, and finish it off with _e.preventDefault();