Reputation: 3
I've made a image slider combined with a counter, every time when a user clicks on a button the image slides and a +1 value gets added in the counter. But at the moment users can spam the button which gives the counter a value of 20 while only 2 images have slided.
So I'm trying to delay the click function for about 500ms so that in coincides with the animation. Or perhaps have the click function disabled untill the animation is done.
At the moment I build a setTimeout into it but it just delays everything, the button is still spamable so that the value in the counter still adds up. It only delays the initial animation/click.
$(".next").click(function(){
setTimeout(function(){
$("body").find(".output").html(function(i, val){return val*1+1});
$("body").parent().find("img:last").stop().animate({'margin-left': '-100%',}, 500,
function(){
$(this).remove();
});
},500)
})
I've created a codepen example if you want to check it out: http://codepen.io/anon/pen/sunKg
Upvotes: 0
Views: 713
Reputation: 873
You have used div as next previous button. Use button tag and you will disable button on click. After that when animation completed you can enable it again...
Upvotes: 2
Reputation: 5722
Use a global variable to store the status of the animation:
JS CODE
var isBusy = false;
$('.next').click(function() {
if(!isBusy) // check if busy
{
isBusy = true; // set busy
//do stuff here
$("body").parent().find("img:last").stop().animate(
{'margin-left': '-100%',},
500,
function(){
// do other stuff here when animation is completed
isBusy = false; // set busy to false
});
},500);
}
});
Other possibility
You can also use the off()
method to remove the click event of the button untill animation is complete. Then enable the event handler again to the button.
More about off() in jquery
Upvotes: 0