Any ideas what here’s wrong? Can’t figure it out… It says that arr is not equal to [17, 67]
var key = function(keys, fn) {
var arr = [];
$(document).on({
keydown: function(e) {
arr.push(e.which);
if (arr === keys) {
fn();
}
},
keyup: function() {
arr = [];
}
});
};
// ctrl + c
key([17, 67], function() {
alert(true);
});
Here’s a fiddle
Update
Since Cymen‘s answer it works, however if you press ctrl + a and then ctrl + alt + a or vice versa you have to fire the second shortcut twice to work, any ideas?
New fiddle.
var key = function(keys, fn) {
var arr = [];
$(document).on({
keydown: function(e) {
arr.push(e.which);
for (var i = 0; keys[i]; i++) {
if (arr[i] !== keys[i]) {
return false;
}
}
fn(e);
arr = [];
},
keyup: function() {
arr = [];
}
});
};
// ctrl + c
key([17, 67], function() {
alert(true);
});
// ctrl + alt + c
key([17, 18, 67], function() {
alert('ctrl+alt+c');
});
You can’t use
===to check if arrays are equal by content. Check it out with a JavaScript console:So
===on arrays is checking the reference not the value. You can use something else like underscore do the comparison or write one yourself if it is some sort of challenge. Or since you’re only comparing two elements, do this:http://jsfiddle.net/9LbsD/
For more than two keys like CTRL+ALT+C
http://jsfiddle.net/WZLut/
A less buggy approach
We need to keep track of which keys were pressed however a single key can only be pressed once in one combination (I’m assuming) and on keyup we should only remove the key going up not all the keys. So here is a working approach to that:
http://jsfiddle.net/BgQUA/