Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect multiple keys on single keypress event in jQuery

Is it at all possible to combine a mixture of keypress' to fire a single event?

$(document).keyup(function(e){     if (e.keyCode == 68 && e.keyCode == 69 && e.keyCode == 86) {         alert('oh hai');     } }); 

I've tried it in Chrome but the event doesn't fire.

Call me crazy but I am writing a Chrome extension and want to push D+E+V keys together to force it into a hidden developer mode.

like image 689
remarsh Avatar asked May 18 '12 15:05

remarsh


2 Answers

If you want to detect that the d, e, and v keys were all down at the same time, you have to watch both keydown and keyup and keep a map of the ones that are down. When they're all down, fire your event.

For example: Live copy | source

var map = {68: false, 69: false, 86: false}; $(document).keydown(function(e) {     if (e.keyCode in map) {         map[e.keyCode] = true;         if (map[68] && map[69] && map[86]) {             // FIRE EVENT         }     } }).keyup(function(e) {     if (e.keyCode in map) {         map[e.keyCode] = false;     } }); 

I assume you don't care what order they're pressed down in (as that would be a pain to reliably press) as long as they're all down at the same time at some point.

like image 163
T.J. Crowder Avatar answered Oct 13 '22 00:10

T.J. Crowder


Similar to Vega's...but simpler

var down = {}; $(document).keydown(function(e) {     down[e.keyCode] = true; }).keyup(function(e) {     if (down[68] && down[69] && down[86]) {         alert('oh hai');     }     down[e.keyCode] = false; });​ 
like image 41
Parth Thakkar Avatar answered Oct 13 '22 00:10

Parth Thakkar