2

I would like to know what key was downed (held and pressed) while a double click event was fired on an element.

The event handler allows me to get alt, shift, meta and ctrl key. What if I want to detect whether 'x' was downed when a double click was made... Or any other letter or number for that matter.

Lumi Lu
  • 3,289
  • 1
  • 11
  • 21
omar-ali
  • 507
  • 4
  • 14

3 Answers3

1

If you want to detect ctrl, alt or shift keys, they are exposed on the event object that is passed to you.

$(document).on('dblclick', function(e){
    /*
     * here you could use e.altKey, e.ctrlKey and e.shiftKey - all of them
     * are bools indicating if the key was pressed during the event.
     */
});

If you want to detect a different key, then omar-ali's answer seems to be the right thing to do.

Yair Tavor
  • 2,538
  • 1
  • 20
  • 16
  • Yes I had known that... as I mentioned in the question, that al, ctrl, meta and shift are doable, but what if... the other chars. I will wait for a little longer to see if someone else has a better idea otherwise, I"ll just mark my own answer as correct. – omar-ali Jan 25 '15 at 10:02
0

One possibility is to do this, 88 = the letter x.. but.. is there a better way.

$(document).on('keydown','body',function(e) {
        //console.log(e.keyCode);
        if(e.keyCode==88)
            keyed = true;

    });

    $(document).on('keyup','body',function(e) {
        if(e.keyCode==88)
            keyed = false;
    });

    $(document).on('dblclick','body',function(e) {
        if(keyed==true)
            alert('yes');
        keyed=false;
    });
omar-ali
  • 507
  • 4
  • 14
0

You must store the keycode until the keyup event, and reference the current value at the time of the double-click event.

var heldKey;
$(document).on({ 
    'keydown' : function(e) {        
        heldKey = e.which || e.keyCode;
    },
    'keyup': function(e) { 
        heldKey = undefined;
    },
    'dblclick': function(e){
        console.log(String.fromCharCode(heldKey));
    }
});
Ben Grimm
  • 4,316
  • 2
  • 15
  • 24