Skip to content

Instantly share code, notes, and snippets.

@Sominemo
Last active May 31, 2018 20:32
Show Gist options
  • Save Sominemo/f78e4904b347439d21fb02a843d62d84 to your computer and use it in GitHub Desktop.
Save Sominemo/f78e4904b347439d21fb02a843d62d84 to your computer and use it in GitHub Desktop.
Listening for pressing keys from string in correct order and giving callback
onword = {
reg: {},
debug: false,
set: (a, c, s) => {
if (!s) a = a.toLowerCase();
document.addEventListener("keypress", (b) => {
onword.listen(a, b, c, s);
});
onword.reg[a] = 0;
},
listen: (a, b, c, s) => {
if (!s) var key = b.key.toLowerCase(); else var key = b.key;
if (a[onword.reg[a]] && key === a[onword.reg[a]]) {
onword.reg[a]++;
if (onword.debug) console.log(key+" === "+a[onword.reg[a]-1]);
} else {
var m = onword.reg[a];
onword.reg[a] = 0;
if (onword.debug) console.log(key+" !== "+a[m]);
}
if (onword.reg[a] >= a.length) {c(); onword.reg[a] = 0;}
}
}
// onword.set(): Add new KeyPress-listener
// @param a* {string} - String we're listening for
// @param c* {function} - Callback
// @param s {bool} - Case-sensitive
onword.set("Hello World", ()=>{alert("Welcome to JavaScript!");})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment