Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

109
Visualizações
How to Stop events adding up in DOM onkeypress Jquery?

I'm trying to animate a div on spacebar keypress which works perfectly fine, but on pressing spacebar multiple times the events get added up in DOM and execute one after another.

I tried to stop recording the recent triggers until the current one executes but failed.

This is the code:

$('body').keypress(function(e){
   if(e.keyCode == 32){
           $(".character").animate({top: '-=300px'}, 500);
           $(".character").animate({top: '+=300px'}, 500);
       }
   }
});

The code I tried with adding a class and removing it to differentiate it :

$('body').keypress(function(e){
   if(e.keyCode == 32){
       if($(".character").hasClass("character_jumping")) { } else {
           $(".character").addClass("character_jumping");
           $(".character_jumping").animate({top: '-=300px'}, 500);
           $(".character_jumping").animate({top: '+=300px'}, 500);
           $(".character").removeClass("character_jumping");
       }
   }
});

The code I tried with event.stopPropagation(); :

$('body').keypress(function(e){
   if(e.keyCode == 32){
           $(".character").animate({top: '-=300px'}, 500);
           $(".character").animate({top: '+=300px'}, 500);
       }
   }
   event.stopPropagation();
});

None worked as I expected. All I'm trying to get is to tell DOM not to record any spacebar keypresses until the character's animation ends.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

stopPropagation didn't work because all that does is stop the event from bubbling to container elements, it doesn't prevent it reaching the handler the event has already called.

Your class solution would work, but you're removing the class too soon. You have to wait for the animation to end, using the animation end callback (docs):

$('body').keypress(function(e){
   if(e.keyCode == 32){
       if ($(".character").hasClass("character_jumping")) { } else {
           $(".character").addClass("character_jumping");
           $(".character_jumping").animate({top: '-=300px'}, 500);
           $(".character_jumping").animate({top: '+=300px'}, 500, () => { // ***
               $(".character").removeClass("character_jumping");          // ***
           });                                                            // ***
       }
   }
});

Another option is to prematurely end the animation with stop and start it again on the keypress.


Side note: It's a matter of style, but I'd suggest using ! rather than an empty if block. The empty if block is very unusual and therefore easily missed:

$('body').keypress(function(e){
   if(e.keyCode == 32){
       if (!$(".character").hasClass("character_jumping")) {              // ***
       //  ^                                                                 ***
           $(".character").addClass("character_jumping");
           $(".character_jumping").animate({top: '-=300px'}, 500);
           $(".character_jumping").animate({top: '+=300px'}, 500, () => {
               $(".character").removeClass("character_jumping");
           });
       }
   }
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda