How to limit to 1 the keydown event in Jquery?

Asked

Viewed 386 times

1

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

But if I keep typing all the time, it’ll add up to more than one every time I keep typing and I’ll get a lot more hits than I should. I wish there was a way to limit it to just once he could do that and block on the others, making him have only one hit.

In the Jsfiddle below, in the case of Alert, it would be as if I were typing the 3 several times the key and adding the hits. In my code there is no Alert and yes at the end he tells me the correct answers http://jsfiddle.net/m3fvL/

$(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', '');

        },

    })});
  • Could you post a Jsfiddle demo? Seeing it running makes it easy for others to give suggestions.

  • 1

    There is no way by a condition only true/false, starts the variable as false and arrow as true, if true Return false and does not execute anything.

  • Done on Jsfiddle, I hope you understand. In the case of Alert, it would be as if I kept typing several times the key and adding the hits that in the case I would like to limit to 1. In my code there is no Alert but at the end he tells me the hits

1 answer

1


Your problem is that you’re in progress, assigning a Handler new to keyup to each animation board. This means that the moment a key is pressed, hundreds of identical copies of your code will run, each of them incrementing acertos - even if only one key has been pressed.

What you need to do is add this Handler only once, on start, and remove it or 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.

  • Thank you for the answer but that’s almost it, take into account that you saw more blocks behind with the same key, in case it would be blocked and I could not type anymore...

  • @user8957 But when the next block appears he will do the bind again, all right? This should be enough - for example, if there is a 5s interval between a block and another, and the user kept pressing "3" straight, will count a hit, then stay 5s without registering anything, and when the next block appears will count a second hit. Now, if you have multiple blocks simultaneously, it gets more complicated...

  • P.S. if you think you can adapt the question by putting more details, do this, otherwise open another - so this does not become one "chameleon question"...

  • That’s right, it’s several blocks of interval 1 second, as more or less happens in a Guitar Hero game.

Browser other questions tagged

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