Give alert after entering the word "pass"

4

How can I perform an alert after the user types "stack".

For example, I'm here posting this and after I write stack (without being an input, just writing) it gives an alert.

I would have to use keypress and which to check the keys being typed, but how can I save each letter until the word hits?

    
asked by anonymous 23.12.2014 / 15:21

2 answers

9

Simply put, this is what you can do:

var memoria = "";
window.onkeyup = function(e) {
    letra = String.fromCharCode(e.keyCode); // Capture a letra digitada
    memoria += letra;                       // Adicione no final da memória
    memoria = memoria.substr(-5);           // Mantenha apenas as 5 ultimas letras
    if (memoria == "STACK") {
        alert("Parabéns!")
    }
}

With each key you type, get the corresponding letter and store it in a string. When the end of this string is the same as the password, do something.

Just take care of cleaning up this memory so that it does not grow absurdly. In this example, a maximum of 5 characters is always kept, as this is the length of the password.

    
23.12.2014 / 15:34
6

My solution is similar to Guilherme Bernal's, but it cleans the key buffer if you take too long between one letter and another:

var intervaloMaximo = 2000;
var timestamp = Date.now();
var palavra = "";

function tecla(e) {
    var agora = Date.now();
    if(agora - timestamp <= intervaloMaximo) {
         palavra += String.fromCharCode(e.which);
    } else {
         palavra = String.fromCharCode(e.which);
    }

    timestamp = agora;
    
    // Seu alert
    if(palavra === 'STACK') alert('stack!');
    
    // monitorando a palavra digitada
    // para fins demonstrativos
    document.getElementById('palavra').innerHTML = palavra;
}

document.addEventListener('keyup', tecla);
<div id="palavra"></div>
    
23.12.2014 / 15:37