Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

107
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda