Last active
August 29, 2015 14:08
-
-
Save goto-dev-null/10cbfa88fe87a08834cf to your computer and use it in GitHub Desktop.
Magic Words lets you effortlessly react to "magic" key sequences on your web page.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Note! Requires jQuery right now :( */ | |
var MagicWords = { | |
spoken: [], | |
data: undefined, | |
init: function(d) { | |
MagicWords.data = d; | |
MagicWords.longest = 0; | |
for(var i in MagicWords.data) { | |
if (typeof MagicWords.data[i].words == 'string' || MagicWords.data[i].words instanceof String) { | |
var x = []; | |
for(var j in MagicWords.data[i].words) | |
x[j] = MagicWords.data[i].words.charCodeAt(j); | |
MagicWords.data[i].words = x; | |
} | |
MagicWords.longest = Math.max(MagicWords.longest, MagicWords.data[i].words.length); | |
} | |
var i = MagicWords.longest | |
while(i-->0) | |
MagicWords.spoken.push(-1); | |
$(document).on("keypress", MagicWords.do_press); | |
$(document).on("keydown", MagicWords.do_down); | |
}, | |
do_press: function(e) { | |
if(e.charCode>0) | |
MagicWords.do_the_do(e.charCode); | |
}, | |
do_down: function (e) { | |
if(e.keyCode == 9 || // Tab | |
(e.keyCode >=37 && e.keyCode <= 40) // Arrow keys | |
) | |
MagicWords.do_the_do(e.keyCode); | |
}, | |
do_the_do: function(n) { | |
MagicWords.spoken.push(n); | |
while(MagicWords.spoken.length>MagicWords.longest) | |
MagicWords.spoken.shift(); | |
var wordWasSpoken = MagicWords.spoken.join(','); | |
for(var i in MagicWords.data) { | |
var wordToTest = MagicWords.data[i].words.join(','); | |
var loc = wordWasSpoken.indexOf(wordToTest); | |
var loc_want = wordWasSpoken.length-wordToTest.length; | |
if(loc>-1 && loc == loc_want) | |
{ | |
MagicWords.data[i].magic(); | |
} | |
} | |
} | |
} | |
/********* Examples *********/ | |
MagicWords.init([{ | |
words: "the googs", | |
magic: function() { window.location.href = 'http://google.com'; } | |
}]); | |
MagicWords.init([{ | |
words: [38, 38, 40, 40, 37, 39, 37, 39, 66, 65], | |
magic: function() { alert('Everyone loves the Konami Code!') } | |
}]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment