Tuesday, May 3, 2011

Konami Code Javascript implementation

I developed this to navigate my site with various shortcuts. My specific implementation can be seen here, and allows various keypress sequences to go to different pages (try typing "home" right now, for example).

What makes this code unique is that there is no ever-increasing array to check against, thus keeping the runtime memory free as can be. It is also extremely flexible and allows for many codes with no slowdown and minimal tweaking (see my linked code above).

Note that this is not tested with Internet Explorer and likely does not work in said browser.


if (window.addEventListener) {

  //konami keypress code, plus as many other codes as you want
  var keyCodes = [[38,38,40,40,37,39,37,39,66,65]];

  //corresponding page(s) to load if the code is correct
  var urls = ["http://www.lotsaoxen.com"];

  //tracks state of keypress (starting at 0)
  var states = [];
  for (i=0; i<keyCodes.length; i++) states[i] = 0;

  window.addEventListener("keydown", function(e) {

    for (i=0; i<keyCodes.length; i++) {
      //if the most recent keypress matches, increment the corresponding state,
      //otherwise reset to zero
      if (e.keyCode == keyCodes[i][states[i]]) states[i]++;
      else states[i] = 0;
      //if the state matches the array length, go to page
      if (states[i] == keyCodes[i].length) window.location = urls[i];
    }

  }, true);

}

0 comments:

Post a Comment