2

I'm trying to build a slider module with JavaScript. Everything works, but the animation is linear, and doesn’t feel smooth or natural. I had thought of hooking up an easing equation, but I'm not sure where it goes.

Here’s the animation function I borrowed from here:

function animate(elem, style, unit, from, to, time) {
    if (!elem) return;
    var start = new Date().getTime(),
        timer = setInterval(function() {
            var step = Math.min(1,(new Date().getTime()-start)/time);

            elem.style[style] = (from+step*(to-from))+unit;

            if (step == 1) clearInterval(timer);
        },25);
    elem.style[style] = from+unit;
}

And an easing function from here:

/**
 * @param {Number} t The current time
 * @param {Number} b The start value
 * @param {Number} c The change in value
 * @param {Number} d The duration time
 */ 
function easeInCubic(t, b, c, d) {
    t /= d;
    return c*t*t*t + b;
}

I tried just passing in the values I already have like this:

elem.style[style] = easeInCubic(start, from, to, time) + unit;

But clearly, that’s wrong (I’m not amazing at maths, and I’m admittedly just guessing).

How do I join the two together?

Community
  • 1
  • 1
Jezen Thomas
  • 13,619
  • 6
  • 53
  • 91

2 Answers2

2

your approach is ok, you just used wrong parameters. as it says, t is current time and d is overall animation time

function animate(elem, style, unit, from, to, time) {
    if (!elem) return;
    var start = new Date().getTime(),
        timer = setInterval(function() {
            var step = Math.min(1,(new Date().getTime()-start)/time);
            elem.style[style] =  easeInCubic(step*time, from,step*(to-from), time)+unit;

            if (step == 1) clearInterval(timer);
        },25);
    elem.style[style] = from+unit;
}
wrm
  • 1,898
  • 13
  • 24
2

tis the current time, or more accurately the elapsed time. In your case new Date().getTime() - start

c is the difference between start and end, in your case from - to.

        var elapsedTime = new Date().getTime() - start;
        elem.style[style] = easeInCubic(elapsedTime, from, to - from, time) + unit;
        if (elapsedTime >= time) clearInterval(timer);
a better oliver
  • 26,330
  • 2
  • 58
  • 66