Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to get the remaining time of animation?

Suppose I have some div, and I use .animate({opacity:0},400, function(){}); for its children. Is it ever possible then to get the remaining time for an animation to complete? eg, 200 ms remaining, or 0 if there's no animation? Thanks.

like image 812
Anonymous Avatar asked May 13 '12 00:05

Anonymous


2 Answers

To help you better understand how you can use the step function [as posted by gdoron]
I created an example using the step function to get the remaining time:

(click the get state! button to stop the animation and retrieve the remaining time!)

demo with distance
demo with opacity

Distance example jQuery:

var time = 4000;
var distance = 300;
var currentTime = 0;

$('#ball').animate({
    left: distance
}, {
    duration: time,
    step: function (now, fx) {

        currentTime = Math.round((now * time) / distance);
        var data = fx.prop + ' ' + Math.round(now) + '; <b>' + currentTime + 'ms</b> ';

        $('body').append('<p>' + data + '</p>');
    },
    easing: 'linear'
});

$('#getTime').click(function () {
    $('#ball').stop();
    $('body').prepend('<p>currentTime is:' + currentTime + ' ms; REMAINING: ' + (time - currentTime) + 'ms</p>');
});
  • You can see how I used the fx.prop inside the animation step to get the (left) property that is currently animated.
  • You can see how: knowing the animation time and the distance (opacity, whatever...) we can easily retrieve the 'stopped/paused' state by some simple math ((now*time)/distance) and thanks to the returned now value.
like image 187
Roko C. Buljan Avatar answered Oct 19 '22 15:10

Roko C. Buljan


I have no idea why do you need it, but the step can help you extract this value:

Step Function

The second version of .animate() provides a step option — a callback function that is fired at each step of the animation. This function is useful for enabling custom animation types or altering the animation as it is occurring. It accepts two arguments (now and fx), and this is set to the DOM element being animated.

now: the numeric value of the property being animated at each step
fx: a reference to the jQuery.fx prototype object, which contains a number of properties such as elem for the animated element, start and end for the first and last value of the animated property, respectively, and prop for the property being animated.

docs

like image 24
gdoron is supporting Monica Avatar answered Oct 19 '22 14:10

gdoron is supporting Monica