Reputation: 633
I am animating div on keypress, but if i press up arrow 2x then my animation breaks, Is there a way i can allow keypress only after 1 second?
$(document).keyup(function(e){
if (e.keyCode == 38) {
$('.selected').animate({'top':'300px'},500);
$('.section.selected').removeClass('selected')
.next('.section').animate({'top':'0'},500)
.addClass('selected');
return false;
}
e.preventDefault();
});
Upvotes: 3
Views: 286
Reputation: 40639
Try this:
$(document).keyup(function(e){
if (e.keyCode == 38 && !$('.selected').is(':animated')) {
$('.selected').animate({'top':'300px'},500);
$('.section .selected').removeClass('selected')
.next('.section')
.animate({'top':'0px','position':'relative'},500)
.addClass('selected');
return false;
}
e.preventDefault();
});
Upvotes: 0
Reputation: 5986
You can find out if any of the elements is animating and cancel the new animation. So put the below code as the first line to your key-up function.
if($(".selected").is(":animated")) return;
Upvotes: 0
Reputation: 9370
Check if elements are being animated before triggering further animations.:
$(document).keyup(function(e){
if (e.keyCode == 38) {
if(!$('.selected').is(':animated')){
$('.selected').animate({'top':'300px'},500);
$('.section.selected').removeClass('selected').next('.section').animate({'top':'0'},500).addClass('selected');
return false;
}
}
e.preventDefault();
});
Upvotes: 1
Reputation: 150020
To implement your requirement as literally as possible:
var allowKeyPress = true;
$(document).keyup(function(e){
if (e.keyCode == 38) {
if (!allowKeyPress)
return false;
allowKeyPress = false;
setTimeout(function() { allowKeyPress = true; }, 1000);
$('.selected').animate({'top':'300px'},500);
$('.section.selected').removeClass('selected').next('.section').animate({'top':'0'},500).addClass('selected');
return false;
}
e.preventDefault();
});
That is, use a flag, allowKeyPress
- on keyup test whether the flag is false
, and if so stop immediately. Otherwise, continue, setting the flag to false
and using setTimeout()
to schedule a function to run after one second to set the flag back to true
, and of course running your animations.
Upvotes: 1