What am I doing wrong? It seems that the array is not cleared after the function was called.
If you press first ctrl+c and then ctrl+alt+c the second function will not called (only if you press it a second time).
var key = function (keys, fn) {
var arr = [];
$(document).on({
keydown: function (e) {
arr.push(e.which);
if (arr.join(', ') === keys) {
fn(e);
arr = [];
}
},
keyup: function (e) {
arr = [];
}
});
};
// ctrl + c
key('17, 67', function (e) {
alert('ctrl+c');
});
// ctrl + alt + c
key('17, 18, 67', function () {
alert('ctrl+alt+c');
});
Here’s a fiddle.
The problem in your code isn’t the array.
Your keyup is not being called because you release the key when you see the alert window
Check the same code working in here: http://jsfiddle.net/WucCQ/1/ – Watch the console log