Search code examples
javascriptvelocity.js

Velocity.js: How to stop a queue but make the element go to its final state?


I would love to stop an animation queue and make the element go to the final state of that queue.

$el.velocity('finish', true) can only make $el go to the end of current animation in the queue but ignore all the remaining animations.

here's a demo maybe better explaining this.


Solution

  • In theory, running an animation queue with a total duration of 0 should play out all the effects instantly. This does not appear to work, but it does for a 1 ms duration.

    ydaniv has pointed out that the Velocity API contains a mock property that, among other things, allows duration: 0 behaviour: mock: true. Velocity.js API for mock.

    I have added three lines to your code (2 in stop function, 1 in start), that use mock to achieve a 0 ms duration:

    $('.stop').click(function (){
      // Stop and clear the animation queue.
      $(".animate").velocity('finish', true);
      // Enable mocking, and play out the animation instantly.
      $.Velocity.mock = true;
      $(".animate").velocity('callout.twirl');
    })
    
    // ...
    
    function start(){
        // Reset the instant mocking, and start the animation properly.
        $.Velocity.mock = false;
        $(".animate").velocity('callout.twirl')
    }
    

    Demo: Codepen (using mock).

    Warning: the animated div can prevent user from being able to click stop. Note that you do still need to finish the animation queue as before.

    My original solution (1 ms duration) is likely not as efficient but does not require resetting mock afterwards. Using mock will also prevent you from testing your UI with it, so I have included the original solution:

    $('.stop').click(function (){
      // Stop and clear the animation queue.
      $(".animate").velocity('finish', true);
      // Play out the animation, effectively immediately.
      $(".animate").velocity('callout.twirl', { duration: 1 });
    })
    

    Demo: Codepen (using 1 ms duration).

    I highly recommend you try to preserve the intended functionality of mock, by either using the more-crude duration approach, or by creating a construct that will manage the mock variable for you, based on your own semi-global setting (i.e. if you have enabled mocking non-locally, temporarily swap the values before and after your variant of finish).