yckart
yckart

Reputation: 33408

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 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.

Upvotes: 4

Views: 222

Answers (2)

Viktor S.
Viktor S.

Reputation: 12815

EDIT: This code is not good as appeared. It 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 pressed keys into global array, you can check if it is pressed when keydown event happens. This works fine for me: http://fiddle.jshell.net/27WGw/2/ (Note that I changed Ctrl+Alt+c to Ctrl+Alt+d as the first one is a global hotkey on my machine)

Upvotes: 2

cacoroto
cacoroto

Reputation: 279

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

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');
});

Upvotes: 2

Related Questions