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.
CodePudding user response:
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");
});
}
}
});