DEV Community

Discussion on: A JavaScript interview question asked at Facebook

Collapse
 
tomshaw profile image
Tom Shaw

With a couple extra parameters.


var el = document.getElementById("myDiv");

function animate(el, totalTime, distance, startTime, position) {
    if (position >= distance) return;

    var expired = (new Date() - startTime) / 1000;
    position = expired * distance / totalTime * 1000; 

    el.style.left = position + 'px';

    requestAnimationFrame(function() {
        animate(el, totalTime, distance, startTime, position);
    });
}

animate(el, 2000, 300, new Date(), 50);

Collapse
 
yairy profile image
Yair

This will only work if the element is absolute positioned.

Collapse
 
tomshaw profile image
Tom Shaw

Have you tried el.style.transform = "translate(x,y)"

Collapse
 
elisabethgross profile image
elisabethgross

Nice! Although this will move the element from a given position, rather than where it is on the page.

Collapse
 
tomshaw profile image
Tom Shaw

Thanks! Another fun challenge would be to add a timing function lerp, similar to cubic-bezier(x1, y1, x2, y2) to vary the speed over the course of the duration. It's a leap forward in complexity but quite doable.