I'm attempting to detect a number of key combinations in javascript. I need to detect Ctrl + Left, Ctrl + Right, Right, and Left.
So far I'm just trying to detect when Ctrl is pressed. Here's what I have (JSFiddle link):
var keys = {};
$(document).keydown(function (e) {
keys[e.which] = true;
printKeys();
});
$(document).keyup(function (e) {
delete keys[e.which];
printKeys();
});
function printKeys() {
var html = '';
for (var i in keys) {
html += '<p>i: ' + i + '</p>'
if (!keys.hasOwnProperty(i)) continue;
if ($.inArray(17, keys) > -1)
html += '<p>ctrl was pressed, return val: ' + $.inArray(17, keys) + '</p>'
}
$('#out').html(html);
}
I guess I don't really understand how JQuery's inArray is supposed to work because when I press any key, it just returns -1. The if statement also evaluates to true while I only want it to do that when Ctrl is pressed. How can I fix this so that my if statement properly detects Ctrl being pressed? I'll be able to figure the rest out once I get that working properly.
EDIT: Changed if-statement to evaluate inArray returning > -1
$.inArray<-- probably a good place to start if you don't understand how it works :)if ($.inArray(17, keys) > -1)Still doesn't pick up 17 being in the array despitehtml += '<p>i: ' + i + '</p>'popping out 17.