Keyboard shortcut

how to check if key combination is pressed with jquery?

will say that I want to trigger a warning only when pressing the up and down arrow keys simultaneously.

right now using:

switch (event.which) { case 40: alert('down'); break; case 38: alert('up'); break; case 37: alert('left'); break; case 39: alert('right'); break; } 
+4
source share
4 answers

Set flags. When one key is omitted, if it is a specific keyCode, set the flag myKeyIsDown = true . When it appears, set the flag to false. When your second key is omitted, if it has a specific key code, and your myKeyIsDown flag is true, you have two keys.

+5
source

I found this useful: How to detect two keystrokes simultaneously from Javascript? . This is pure javascript. You can also change the first method of working with event.which . And no flags.

Correction: for the first method of working 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) 
+3
source

You can try using a plugin like this ( demo )

+2
source

In one answer to another answer, you may need to stop the cascade of the event during the second key press, which can be done similarly to this: (put your logic, of course)

 /* handle special key press */ function checkCptKey(e) { var shouldBubble = true; switch (e.keyCode) { // user pressed the Tab case 9: { $(".someSelect").toggleClass("classSelectVisible"); shouldBubble = false; break; }; // user pressed the Enter case 13: { $(".someSelect").toggleClass("classSelectVisible"); break; }; // user pressed the ESC case 27: { $(".someSelect").toggleClass("classSelectVisible"); break; }; }; /* this propogates the jQuery event if true */ return shouldBubble; }; /* user pressed special keys while in Selector */ $(".mySelect").keydown(function(e) { return checkCptKey(e); }); 
+1
source

Source: https://habr.com/ru/post/1300745/


All Articles