Resetting an array to an empty array does not work

What am I doing wrong? It seems that the array is not cleared after the function call.

If you press ctrl + c first and then ctrl + alt + c , the second function will not be 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 the fiddle .

+4
source share
2 answers

The problem in your code is not an array.

Your keyboard does not get called because you release the key when you see a warning window

Check out the same code that works here: http://jsfiddle.net/WucCQ/1/ - See console log

 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) { console.log('ctrl+c'); }); // ctrl + alt + c key('17, 18, 67', function () { console.log('ctrl+alt+c'); }); 
+2
source

EDIT: This code is not very good as it appeared. He will not see the difference between Ctrl + C and Cltrl + C + V !

Try this code:

 var key = function (keys, fn) { $(document).on({ keydown: function (e) { var arr = []; if(e.ctrlKey) arr.push("17"); if(e.altKey) arr.push("18"); arr.push(e.which); if (arr.join(', ') === keys) { fn(e); } } }); }; // ctrl + c key('17, 67', function (e) { alert('ctrl+c'); }); // ctrl + alt + d key('17, 18, 68', function () { alert('ctrl+alt+c'); }); 

Instead of collecting the keys pressed into a global array, you can check if it is pressed when the keydown event occurs. This works fine for me: http://fiddle.jshell.net/27WGw/2/ ( Note that I changed Ctrl + Alt + c to Ctrl + Alt + d since the first is a global hotkey on my machine)

+2
source

All Articles