I tried making an animation that if the user clicks next and it reaches to an image that is hidden, the jQuery animation will take effect to display the next batch of images. Like for example if I have six images and the first three images are displayed, if the user clicks for the fourth time, it will now scroll to view the last three images. Now, I only want to use the animation once. The problem is, it will still continue to animate every time I click the button. How to only use the animation once?
Here is the script:
next.onclick = function(){
document.getElementById("defaultPic").src = srcArray[(counter + 1) % numImages];
counter++;
if(counter == 5) {
document.getElementById('next').disabled = true;
document.getElementById('next').style.opacity = '0.5';
document.getElementById('prev').disabled = false;
document.getElementById('prev').style.opacity = '1';
}
if(counter == 2) {
$(function() {
$('#next').on('click', function () {
$('#imageList').stop().animate({left : '-=285px'}, 1000);
});
});
}
}
var animation = true;
next.onclick = function() {
document.getElementById("defaultPic").src = srcArray[(counter + 1) % numImages];
counter++;
if (counter == 5) {
document.getElementById('next').disabled = true;
document.getElementById('next').style.opacity = '0.5';
document.getElementById('prev').disabled = false;
document.getElementById('prev').style.opacity = '1';
}
if (counter == 2) {
$(function() {
$('#next').on('click', function() {
if (animation) {
animation = false;
$('#imageList').stop().animate({
left: '-=285px'
}, 1000, function() {
animation = true;
}););
}
});
});
}
I have set up a global boolean called animation which is set to true, then on click, check if animation is true, if so set it to false and play animation, the .animation()
has also a callback function which specifies when animation has been completed once completed set the animation variable back to true so next click can play the animation again if needed, if you don't want it to be playable again, just remove the variable and/or whole callback function.
.animation() docs
Just slightly improve your event registration:
$(next).one('click', function(){
document.getElementById("defaultPic").src = srcArray[(counter + 1) % numImages];
counter++;
if(counter == 5){
document.getElementById('next').disabled = true;
document.getElementById('next').style.opacity = '0.5';
document.getElementById('prev').disabled = false;
document.getElementById('prev').style.opacity = '1';
}
if(counter == 2){
$(function () {
$('#next').on('click', function () {
$('#imageList').stop().animate({left : '-=285px'}, 1000);
});
});
}
})