Search code examples
javascriptjqueryinputkeypress

jQuery/javascript specific word detect


I am wondering if it's possible to detect words input. I have 2 options:

  1. The word to be written in an input, and at Enter press to fire a certain command like animate or go to url.

  2. 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.


Solution

  • Add a keypress listener to body, append the chars to a string and compare 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.net/9GC4N/