javascript - Execute function only by correct series of keys -
i'm not professionally, out of curiosity since recently. have basic of basic knowledge.
my current experiment this; can program series of keys, execute specific function, , in correct order? i'm saying game combo (ie: famous konami code easter egg, consisting of '↑', '↑', '↓', '↓', '←', '→', '←', '→', 'b', 'a', , 'start')
if, say, use 'onkeydown' this, registers 1 key, not taking regard keys pressed earlier or after (or believe). if not, have somehow record came before and... waaaay out of little fishies league.
is there way such thing, simpler , easier? please don't expect me know much, , please no jquery or such js library :d usage.
could script in konami code example? js char codes pattern 38 38 40 40 37 39 37 39 66 65 13, replacing nintendo 'start' 'enter' key.
here's working example, if mess up, can restart sequence , forgive you. also, if want different combination, change "keys".
<!doctype html> <html> <head> <script> var keys=[38,38,40,40,37,39,37,39,66,65]; var buff=[]; function collect(e){ buff.push(e.keycode); if(buff.length>keys.length){ buff=buff.splice(1); } if(keys==buff.tostring()){ alert("let's play!"); } e.preventdefault(); e.stoppropagation(); } </script> </head> <body> <div contenteditable=true onkeydown="collect(event)">click here accept keystrokes</div> </body> </html>
i put key capture in div, can add document.body instead , listen everywhere on page.
Comments
Post a Comment