Webページ上でコナミコマンドを入力させるもの

http://journal.mycom.co.jp/news/2009/05/12/055/index.html
Webページ上でコナミコマンドを入力させるのが流行ってきているようなので、ちょっと作ってみました。

サンプルページ

Command 573

使い方

IE
document.attachEvent('on573', function () { /* hoge */ });
IE以外
document.addEventListener('573', function () { /* hoge */ }, false);

ライブラリのソース

(function () {
  var isIE = '\v'=='v';
  var command573 = [38,38,40,40,37,39,37,39,66,65];
  var fList = [];
  var n = 0;
  var timeoutId = null;
  
  function f(event) {
    event = event || window.event;
    clearTimeout(timeoutId);
    
    if (event.keyCode == command573[n]) {
      n++;
      if (n == command573.length) {
        n = 0;
        if (isIE) {
          for (var i = 0, length = fList.length; i < length; i++) {
            fList[i]();
          }
        } else {
          var evt = document.createEvent('HTMLEvents');
          evt.initEvent("573", true, true);
          event.target.dispatchEvent(evt);
        }
      } else {
        timeoutId = setTimeout(function () { n = 0; }, 1000);
      }
    } else {
      n = 0;
    }
    
  };
  if (isIE) {
    document._attachEvent = document.attachEvent;
    document.attachEvent = function (n, f) {
      if (n == 'on573') {
        if (typeof f == 'function') { fList.push(f); }
      } else {
        this._attachEvent(n, f);
      }
    }
    
    document._detachEvent = document.detachEvent;
    document.detachEvent = function (n, f) {
      if (n == 'on573') {
        for (var i = 0, length = fList.length; i < length; i++) {
          if (fList[i] == f) { fList.splice(i, 1); break; }
        }
      } else {
        this._detachEvent(n, f);
      }
    }
    
    document.attachEvent('onkeydown', f);
    
  } else {
    document.addEventListener('keydown', f, false);
  }
})();

大したものでもないので、ご自由にお使いください。

あとがき

IEのon573への対応方法は、我ながらかなり無理があると思う。