0

I have an array with keyboard combinations and this should validate to press keys exactly in the order of the array example

var listkeys = ['left', 'right', 'bottom', 'top'];

if(validate key){
    continue
}

the order of the array is important if they are wrong by pressing in the order of the arrows then as I continued not more and sends you an error

I am a newbie in javascript I hope I can help enormously grateful

Josh
  • 8,082
  • 5
  • 43
  • 41
jpmaster
  • 77
  • 1
  • 7

1 Answers1

1

Typically, I don't respond to posts that ask for Do-It-All solutions, but I wrote it out and didn't want it to go to waste. Here is a little something to get you started.

// Valid combination of keys
var valid_combo = ['left', 'right', 'bottom', 'top']; 

// Stack that stores the last 4 key inputs, including non-arrow keys
var history = [];  

// Maps arrow key direction strings to char code
var keys = []; 

keys[37] = 'left';
keys[38] = 'top';
keys[39] = 'right';
keys[40] = 'bottom';

$(window).keyup(function(e) {

    var key = e.which;

    if (key >= 37 && key <= 40) 
    {
        history.push(keys[key]);
    }
    else
    {
        history.push("derp");
    }

    if (history.length > 4) history.shift();

    // Array equality using Option 1 - http://stackoverflow.com/a/10316616/773702
    if (JSON.stringify(valid_combo) == JSON.stringify(history)) 
    {
        console.log("Valid key combination");
    }
});

See it in action on jsFiddle

Josh
  • 8,082
  • 5
  • 43
  • 41
  • I appreciate you for taking the time to write the code, you are a genius! – jpmaster May 13 '13 at 22:29
  • We apologize for the hassle, as it would be if you want to validate with the enter key if you pressed the correct arrows? – jpmaster May 13 '13 at 22:44
  • Add in a check for the [enter key](http://www.w3.org/2002/09/tests/keys-cancel2.html?) then do your validation. :) Cheers! – Josh May 14 '13 at 12:25