-1
document.onkeyup = function(event){

    var key_press = String.fromCharCode(event.keyCode);
    var status = document.getElementById('status');
    status.innerHTML = "UP Event Fired For : "+key_press;
    if (key_press == "38") {
        &&
    } if (key_press == "39") {
        &&
    } else if (key_press == "40") {
        &&
    } else if (key_press == "37") {
        alert ("First born beauty");
    }
});
}

Hello, I try to make the purpose of this code to action event/popup when arrow keys have been pressed in the right order (left>up>right>down) important that it is body that listens. :)

http://jsfiddle.net/50hup6y1/7/

Barmar
  • 741,623
  • 53
  • 500
  • 612
CreativeCreator
  • 220
  • 1
  • 9
  • Welcome! You forgot to ask a question though. What's the problem you're having with the code? – JJJ Sep 30 '14 at 15:23
  • Your code isn't even valid Javascript syntax. You can't have `&&` as the entire statement in an `if` body. – Barmar Sep 30 '14 at 15:26
  • Also, you have an extra parenthesis and brace at the end of the function. – Barmar Sep 30 '14 at 15:27
  • @Barmar: I think (hope) it's a pseudo-code, or perhaps a profound misunderstanding of using `if (condition1 && condition2)`, but...who knows? – David Thomas Sep 30 '14 at 15:27
  • 1
    @Barmar Yes, that's why OP is asking how to make sure keys are press in specified order. This is just a pseudo code, right. – dfsq Sep 30 '14 at 15:28
  • 2
    Open of your browsers developer tools and you'll be able to see some errors related to your code. – Cory Danielson Sep 30 '14 at 15:28
  • Set a variable to the previous key codes, and then check if the current key code is the next one in the sequence. – Barmar Sep 30 '14 at 15:29

2 Answers2

1

I wouldn't mind seeing other responses, but this is, naively, what I came up with:

var keyQueue = [];

function checkQueue() {
    // just remove old keys until we only have 4
    // this is to keep the queue from growing too big
    // note the '4' should be the longest combination of
    // keys you plan to use
    while(keyQueue.length > 4) {
        keyQueue.shift();
    }

    if (keyQueue[0] === 37
        && keyQueue[1] === 38
        && keyQueue[2] === 39
        && keyQueue[3] === 40) {
        alert("Hey the keys were pressed in the right order!")
    }
}

document.onkeyup = function(event) {
    keyQueue.push(event.keyCode);
    checkQueue();
};

Generally speaking, onkeyup stores the key presses in a queue. Then checks to see if the last 4 presses were both the right keys, and in the right order. If so, something happens.

klyd
  • 3,939
  • 3
  • 24
  • 34
1

My own take on the problem would be:

// taken from: http://stackoverflow.com/a/14853974/82548
// attach the .equals method to Array's prototype to call it on any array
Array.prototype.equals = function (array) {
    // if the other array is a falsy value, return
    if (!array)
        return false;

    // compare lengths - can save a lot of time 
    if (this.length != array.length)
        return false;

    for (var i = 0, l=this.length; i < l; i++) {
        // Check if we have nested arrays
        if (this[i] instanceof Array && array[i] instanceof Array) {
            // recurse into the nested arrays
            if (!this[i].equals(array[i]))
                return false;       
        }           
        else if (this[i] != array[i]) { 
            // Warning - two different object instances will never be equal: {x:20} != {x:20}
            return false;   
        }           
    }       
    return true;
}   


// the keys to be pressed, in the order to be pressed:    
var keyOrder = [37,38,39,40],
// the log of keys the user presses:
    keyPresses = [];

function keySequenceCheck (e) {
    // adding the last-pressed key to the array:
    keyPresses.push(e.keyCode);

    // if the keyPresses array is long the key order we're checking for, we
    // we trim off the front of the array:
    if (keyPresses.length > keyOrder.length) {
        keyPresses.shift();
    }

    // checking that the keyPresses array has the same values
    // in the same order as the keyOrder array:
    if (keyPresses.equals(keyOrder)) {
        // if so display the message:
        console.log('Message');
    }
}

// bind the event handler to the <body> element:
document.body.addEventListener('keyup', keySequenceCheck);

// taken from: http://stackoverflow.com/a/14853974/82548
// attach the .equals method to Array's prototype to call it on any array
Array.prototype.equals = function(array) {
  // if the other array is a falsy value, return
  if (!array)
    return false;

  // compare lengths - can save a lot of time 
  if (this.length != array.length)
    return false;

  for (var i = 0, l = this.length; i < l; i++) {
    // Check if we have nested arrays
    if (this[i] instanceof Array && array[i] instanceof Array) {
      // recurse into the nested arrays
      if (!this[i].equals(array[i]))
        return false;
    } else if (this[i] != array[i]) {
      // Warning - two different object instances will never be equal: {x:20} != {x:20}
      return false;
    }
  }
  return true;
}


var keyOrder = [37, 38, 39, 40],
  keyPresses = [];

function keySequenceCheck(e) {
  keyPresses.push(e.keyCode);
  if (keyPresses.length > keyOrder.length) {
    keyPresses.shift();
  }

  if (keyPresses.equals(keyOrder)) {
    console.log('Message');
  }
}

document.body.addEventListener('keyup', keySequenceCheck);
body {
  height: 100%;
  background-color: #ffa;
}

JS Fiddle demo.

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • Nice, though I do suggest avoiding the ["monkey patch"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain#Bad_practice.3A_Extension_of_native_prototypes) on `Array.prototype`. Putting that code in a separate object without modifying `Array` would obviously work just as well. – klyd Sep 30 '14 at 15:51
  • Hmm, it's not an ideal practice, I agree, but I'd rather do it this way (rather than, for example, `arrayEquals(array1,array2)`). To my mind it comes down to personal preference (and team coding convention, obviously). – David Thomas Sep 30 '14 at 15:53