I am wondering if it's possible to detect words input. I have 2 options:
The word to be written in an input, and at Enter press to fire a certain mand like animate or go to url.
The word to be written anywhere on the page, like GTA cheats, or some YouTube Easter Eggs.
If I'm not being clear, just say and i'll edit.
I am wondering if it's possible to detect words input. I have 2 options:
The word to be written in an input, and at Enter press to fire a certain mand like animate or go to url.
The word to be written anywhere on the page, like GTA cheats, or some YouTube Easter Eggs.
If I'm not being clear, just say and i'll edit.
Share edited May 4, 2014 at 20:31 animuson♦ 54.8k28 gold badges142 silver badges150 bronze badges asked Aug 11, 2013 at 9:43 yomisimieyomisimie 3933 silver badges16 bronze badges 4- when you mean written, do you mean just to detect a series of keypresses anywhere on the page? – Justin L. Commented Aug 11, 2013 at 9:45
- Yes, it's possible. Are you having problems with your implementation? – Blender Commented Aug 11, 2013 at 9:49
- @JustinL. Yes, a series of keys. Or a word in the input. – yomisimie Commented Aug 11, 2013 at 9:54
- @Blender Yes, can you help me with some code? An example? – yomisimie Commented Aug 11, 2013 at 9:55
3 Answers
Reset to default 6Add a keypress listener to body, append the chars to a string and pare it to a target word:
var word = "hello";
var input = "";
document.body.addEventListener('keypress',function(ev){
input += String.fromCharCode(ev.keyCode);
console.log(input);
if(input == word){
alert('typed hello');
input = "";
}
});
// reset input when pressing esc
document.body.addEventListener('keyup',function(ev){
if(ev.keyCode == 27) input = "";
});
Demo:
http://jsfiddle/9GC4N/
An improvement:
var seq = "rainbow"
var input = ""
window.addEventListener("keypress", function(e) {
input += String.fromCharCode(e.keyCode)
for (var i = 0; i < seq.length; i++) {
if (input[i] != seq[i] && input[i] != undefined) {
input = ""
}
}
if (input == seq) {
alert("EASTER EGG!")
input = ""
}
})
I think it makes more sense to use a queue as that way we always pare the last x characters with the target sequence after every key press.
E.g.
var seq = 'upsidedown';
var input = '';
window.addEventListener('keypress', function(e) {
// Add the latest character to the end of the queue
input += String.fromCharCode(e.keyCode);
// If the queue is longer than the target sequence remove the first character
if(input.length > seq.length) {
input = input.substr(1);
}
// Check for a match
if(input == seq) {
alert("EASTER EGG!")
}
})