Alex Rivera | Logout

jQuery detect keystrokes and set variables accordingly

Asked 2010-03-02T15:00:47.233
9

I have created a rudimentary EasterEgg within my code to activate when the following keystrokes are made (not simultaneously) Enter + c + o + l + o + r + s with the following code:

isEnter = 0; isC = 0; isO = 0; isL = 0; isR = 0; isS = 0;
$(window).keydown(function(e){
    if(e.which==13) isEnter = 1; if(e.which==67) isC = 1; if(e.which==79) isO = 1; 
    if(e.which==76) isL = 1; if(e.which==82) isR = 1; if(e.which==83) isS = 1;
    ColorMap();
});

function ColorMap(){
  if(isEnter==1 && isC==1 && isO==1 && isL==1 && isR==1 && isS==1){
     //DO FUNCTION//
     isEnter = 0; isC = 0; isO = 0; isL = 0; isR = 0; isS = 0; //SET VARS BACK TO 0
  };
};

I need to add reset functionality to the keydown function to reset all variables if something other than those keys are pressed... that way they have to press Enter + c + o + l + o + r + s or the statement gets reset and they have to start again...(this will make the 'EasterEgg' harder to get to [or at least less likely to get to by fluke or random keystrokes]).

Edit
Report

1 Answer

3

I answered a similar easter egg question recently, so I'll just point you to that one.

It takes a different approach that what you're doing, and it doesn't need to be reset.

Javascript/jQuery Keypress logging

EDIT: Here's an updated version that keeps the key history from getting too long.

$(document).ready(function() {

    var easterEgg = 'egg';
    var eggLength = easterEgg.length;
    var keyHistory = '';
    var match;
        $(document).keypress(function(e) {
            keyHistory += String.fromCharCode(e.which)
            match = keyHistory.match(easterEgg); 
            if(match) {
                alert(match);
                keyHistory = match = '';
            } else if (keyHistory.length > 30) {
                keyHistory = keyHistory.substr((keyHistory.length - eggLength - 1));
            }
        });
});
answered 2010-03-02T15:15:05.350

Your Answer