CUDA CUDA - 3 years ago 313
Javascript Question

JavaScript animation

I am trying to animate a

div
moving
200px
horizontally in JavaScript.

The code below makes it jump the pixels, but is there a way to make it look animated without using jQuery?

function () {
var div = document.getElementById('challengeOneImageJavascript');
div.style.left = "200px";
}

Answer Source

Here is a basic animation setup:

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;
}

To use:

animate(
    document.getElementById('challengeOneImageJavascript'),
    "left","px",0,200,1000
);

This example will animate the given element to slide linearly from 0px to 200px over a time of 1 second (1000 ms).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download