Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keydown combination

Tags:

jquery

how do i check if a combination of keys are pressed with jquery?

lets say i want to fire up an alert only when the up and down arrow keys are pressed at the same time.

right now im just using:

switch (event.which) {
    case 40:
        alert('down');
        break;
    case 38:
        alert('up');
        break;
    case 37:
        alert('left');
        break;
    case 39:
        alert('right');
        break;
}
like image 814
ajsie Avatar asked Dec 23 '22 05:12

ajsie


2 Answers

Set flags. When one key goes down, if it's a certain keyCode, set your flag myKeyIsDown = true. When it comes up, set the flag back to false. When your second key goes down, if it is of a certain keyCode and your myKeyIsDown flag is true, you've got two keys down.

like image 53
Sampson Avatar answered Jan 02 '23 09:01

Sampson


I found this useful: How to detect simultanious two key press from the Javascript ?. It's pure javascript though. You can also change first method to work with event.which. And no flags.

Fix: For first method to work with up + down + R, you should use this method:

function KeyPress(e) {
    for (i = 0; i < KPAry.length; i++) {
        if (e == KPAry[i]) {
            return;
        }
    } // for (i=0;i<KPAry.length;i++)

    if (e != 17 && e != 18 && e != 82 && e!=38 && e!=40) {
        KPAry = new Array();
    } else {
        KPAry[KPAry.length] = e;
    }
    if (KPAry.length == 3) {
        if (KPAry[0] == 17 && KPAry[1] == 18 && KPAry[2] == 82) {
            alert('Keys Pressed\nctrl+alt+R ');
        } else if (KPAry[0] == 38 && KPAry[1] == 40 && KPAry[2] == 82) {
            alert('Keys Pressed\nup+down+R ');
        }
        KPAry = new Array();
    } // if (KPAry.length==3)
} // function KeyPress(e)
like image 26
Andriy F. Avatar answered Jan 02 '23 09:01

Andriy F.