Matteo Gilardoni
Matteo Gilardoni

Reputation: 341

activate an event on the button only after the animation has finished

I create a button that when it is clicked, moves some images but when I click quickly the button, jQuery create an error on the movement of the images. So I want disable the button untill that the .animate() function isn't finish. I tryed write this code but isn't correct.

var next = $('.next');

function nextAction(e){
    e.preventDefault();
    next.off('click');
    if(pellicle.css('left').replace(/[^-\d\.]/g, '') <= -(stepTotalWidth - screenWidth)){
        pellicle.animate({
            left:'0'
        },1000, function(){next.on('click', nextAction);});
    }
    else {
        pellicle.animate({
            left:'-=' + screenWidth
        },1000);
    }
}

next.on('click', nextAction);

Upvotes: 0

Views: 171

Answers (2)

Matteo Gilardoni
Matteo Gilardoni

Reputation: 341

Perfect solution by Flops, here there is complete code

//next button
function nextAction(e){
    next.off('click', nextAction); //detach by link on function
    e.preventDefault();
    if(parseInt(pellicle.css('left')) <= -(stepTotalWidth - screenWidth)){
        pellicle.animate({
            left:'0'
        },1000, function(e){next.on('click', nextAction);});
    }
    else {
        pellicle.animate({
            left:'-=' + screenWidth
        },1000, function(e){next.on('click', nextAction);});
    }
}
next.on('click', nextAction);

Upvotes: 0

Flops
Flops

Reputation: 1420

You can attach and detach events as many as you want, i didn't get what is the question exept that you have o problem with click in period when you 'off' event while animation running.

For this you can attach another event that will prevent default and second will run animanion

function nextAction(e){
    next.off('click.gallery'); //detach by namespace
    next.off('click', nextAction); //detach by link on function

    //Your code and again attach animation click
}


next.on('click', function(e){ 
  e.preventDefault(); 
});

next.on('click.gallery', nextAction); 
/* .gallery is not necessary if you will detach events 
by the link on the function that attached to that */

The second thing is that pellicle.css('left') is always returns ***px in that case a bit faster than regexp would be parseInt(pellicle.css('left'), 10) || 0 it will always give you a number in that case.

Upvotes: 1

Related Questions