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.