John John - 4 months ago 24
Javascript Question

Ignore click event when Velocity JS animation is running

I'm using Velocity JS but when I click on a button who trigger an animation if I click 10 times on this button the animation will be repated 10 times.

How it's possible to ignore the click event if an animation is running ?

I tried

event.stopPropagation
and
event.preventDefault
but there is no effect.

I tried too
velocity.('stop', true)
but this will stop the animation and restart it at the last position and it looks like a "lag" if I click 10 times on my button.

Then here is my code :

$('#btn_animate').on('click', function(e){

divs.velocity('transition.flipXOut',
{
duration :500,
complete: function() {
$('#box2').velocity('transition.flipXIn', {duration :800})
}
})

});


How can I do to avoid the click event when a Velocity JS animation is running ?

Answer

I had to read on a little about Velocity...

You did not provide the "effect registration" part.
I took it in the Velocity examples

$.Velocity
    .RegisterEffect("transition.flipXIn", {
        defaultDuration: 700,
        calls: [
            [ { opacity: 1, rotateY: [ 0, -55 ] } ]
        ]
    });
$.Velocity
    .RegisterEffect("transition.flipXOut", {
        defaultDuration: 700,
        calls: [
            [ { opacity: 0, rotateY: 55 } ]
        ],
        reset: { rotateY: 0 }
    });

So now, let's define a function that which called "theEffect".
This function does:

  • unbind click events from the button
  • do the animation
  • do the animation callback (which is another animation)
  • re-binds `click` events to the button in the second animation callback.
var theEffect = function(){
    console.log("UNBINDING click events from the button");
    $('#btn_animate').unbind("click");

    $('#box2').velocity('transition.flipXOut',{
        duration:500,
        complete: function() {
            $('#box2').velocity('transition.flipXIn', {
                duration:800,
                complete: function() {
                    console.log("BINDING click events to the button");
                    $('#btn_animate').bind("click",theEffect);
                }
            });
        }
    });
}
// Initial binding
$('#btn_animate').bind("click",theEffect);

I got it working in this CodePen.
(with longest durations)