Created
January 9, 2019 20:00
-
-
Save theverything/8f71829fbcf200d92c3e07525cc2ca94 to your computer and use it in GitHub Desktop.
Konami Code
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
function konamiCode(cb) { | |
const UP = 38; | |
const DOWN = 40; | |
const LEFT = 37; | |
const RIGHT = 39; | |
const KONAMI_CODE = [UP, UP, DOWN, DOWN, LEFT, RIGHT, LEFT, RIGHT].join('-'); | |
let keypresses = []; | |
let enabled = false; | |
let rootEl = null; | |
let passive = false; | |
try { | |
const options = { | |
get passive() { | |
passive = true; | |
} | |
}; | |
window.addEventListener("test", options, options); | |
window.removeEventListener("test", options, options); | |
} catch(err) { | |
passive = false; | |
} | |
function handler(event) { | |
keypresses.push(event.keyCode); | |
if (keypresses.length === 8) { | |
if (keypresses.join('-') === KONAMI_CODE) { | |
cb(); | |
keypresses = []; | |
} else { | |
keypresses = keypresses.slice(1, 8); | |
} | |
} | |
} | |
window.addEventListener('keydown', handler, passive ? { passive: true } : false); | |
return function() { | |
window.removeEventListener('keydown', handler); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment