Give Alert after typing the word "pass"

Asked

Viewed 125 times

4

How can I run an Alert after the user writes "stack".

For example, stack (without being an input, just writing) it gives an Alert.

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

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 keystroke, get the corresponding letter and store it in a string. When the end of this string matches the password, do something.

Just take care to wipe that memory so it doesn’t grow absurdly. In this example, it is always kept at a maximum of 5 characters, since this is the length of the password.

  • You could put memoria = ''; within the if so Alert fires every time a new word occurrence appears

  • 1

    @renatoargh Does not shoot, because the next letter typed will change the memory.

  • Oh man, now I get it! + 1

6

My solution is similar to Guilherme Bernal’s, but clears the keystroke buffer if you take too long between a 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>

  • Good. Even in terms of usability. User has short term memory, if he type "CK" and suddenly appears Alert he will not understand that password is STACK.

  • @bfavaretto Because you and @Guilherme Bernal chose to keyup instead of keypress or keydown?

  • @renatoargh In my case, as a matter of habit, and because I find it more natural to react to what was typed only after taking your finger off the key.

  • @renatoargh This way Alert will not appear while the user is still holding the key. It may get a little conflicting otherwise.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.