hybrid9
hybrid9

Reputation: 2636

setInterval counter with jQuery animate

I'm developing a pseudo timeline of distance with an tooltip that follows the timeline to a new marker position.

 |--------- 800px ------|------------------- 1200px ----------- |
 A (5000km)             B (20000km)                             C (30000km)

Between marker A (5000km) and marker B is a faux difference of 15000km, but the real distance between the elements on the timeline is 800px. I animate an indicator with a counter that moves along those two points in the span of 12 seconds. The animation is simple, but I can't figure out the counter interval so it starts at 5000 and ends at 20000 during the 12 second timeframe.

Here's what I have, but the counter finishes way behind the animation because I can't solve for the increment value.

var ttl = 12*1000,
    startKM = 5000,
    endKM = 15000,
    diffDist = endKM-startKM,
    distanceLoop,
    txt = $('.counter').text();
    increment = diffDist/ttl;

$('.counter').text(startKM);

$('.indicator').animate({ left: $('.markB').offset().left }, ttl, 'linear', function() {
    clearInterval(distanceLoop);
});

function counterLoop() {

    var num = txt++;
    // what is the count interval 
    // var num = txt + increment
    $('.counter').text(num);
};

distanceLoop = setInterval(counterLoop, diffDist/ttl )

counterLoop();

I don't know what the increment is so right now its just +1 to the counter. This probably something basic, that I'm just not seeing.

Thanks for the help!

Demo/Fiddle: http://jsfiddle.net/7xygy/10/

Upvotes: 2

Views: 530

Answers (1)

John S
John S

Reputation: 21482

You could use the step option of the .animate() function, rather than setInterval.

var startKM = 5000,
    endKM = 15000;

var startLeft = $('.indicator').offset().left,
    endLeft = $('.markB').offset().left,
    ratio = (endKM - startKM) / (endLeft - startLeft);

$('.counter').text(startKM);
$('.indicator').animate({ left: endLeft }, {
    easing: 'linear',
    duration: 12000,
    step: function(now) {
        $('.counter').text(Math.floor(startKM + ((now - startLeft) * ratio)));
    },
    complete: function() {
        $('.counter').text(endKM);
    }
});

jsfiddle

Upvotes: 3

Related Questions