How to limit the 1 keydown event in JQuery?

1

I made a code that when starting my event, it makes a block make a move from top to bottom. If he presses the "3" key between the pixels set during the animation, he causes the animation to be removed and received "1 hit".

But if I keep typing all the time, it will add up to 1 each time I'm typing and I'm going to have a lot more successes than I should. I would like to limit it to only once he can do this and block the others, making him only have 1 single hit.

In the JSFiddle below, in the case of the alert, it would be like if I kept typing the 3 key several times and adding the correct answers. In my code there is no alert but in the end he tells me the correct answers link

$(function cair() {
    $(".blococair").fadeTo( 500, 1 ); 
    $(".blococair").animate({
        top: fim + "px",
        },{
        duration: 5000,
        start: function () {
            inicio = window.getComputedStyle(this).top.replace('px', '');
        },
        progress: function (a, p, r) {
            var valorAtual = p * (fim - inicio);
            $(document).keyup(function(e) {
                if (e.which == 53 && Math.round(valorAtual) < 295) {
                } else if (e.which == 53 && Math.round(valorAtual) >= 296 && Math.round(valorAtual) <= 315) {
                    $('.blococair').remove();
                    acertos++;
                }})
        },


        "complete" : function() {
                      $('.blococair').remove();
        },

        start: function () {
            inicio = window.getComputedStyle(this).top.replace('px', '');

        },

    })});
    
asked by anonymous 27.05.2014 / 20:32

1 answer

1

Your problem is that you are in progress , assigning a new handler to keyup to each animation frame. This means that, as soon as a key is pressed, hundreds of identical copies of your code will execute, each incrementing acertos - even if only a single key has been pressed.

What you need to do is add this handler only once, in start , and remove it either in the complete or the moment a key is pressed.

var valorAtual; // Movi para cá, para que a função testarAcerto possa acessá-la

function testarAcerto(e) {
    if (e.which == 51 && Math.round(valorAtual) > 0) {
        $('.cair').remove();
        acertos++;
        alert(acertos);
        $(document).unbind("keyup"); // Já acertou, não ouça mais por eventos keyup
    }
}

...

    start: function () {
        inicio = window.getComputedStyle(this).top.replace('px', '');
        $(document).bind("keyup", testarAcerto); // Coloca o handler no começo
    },
    progress: function (a, p, r) {
        valorAtual = p * (fim - inicio); // Só atualiza o valor no progress
    },

    "complete": function () {
        $('.cair').remove();
        $(document).unbind("keyup"); // Remove o handler no final
    },

Example in jsFiddle .

    
27.05.2014 / 21:56