Vanilla JS position animation
Every 25 millisconds Define step as the proportion of the desired duration Increase the style of the element by that proportion times the difference between the start and finish values So if the finish value needs to be bigger than the start value and we're three quarters of the way through the duration, the style should be set to three quarters of the difference between the start and finish values If the finish value needs to be smaller the same thing applies - if we're three quarters of the way through and we're shrinking a box of 100 to 10 we set the style to the from value plus three quarters times 10 - 100, so three quarters of -90. Therefore the from style is reduced by 0.75 times 90.
by andfinally
HTML
<div id="challengeOneImageJavascript"></div>
CSS
#challengeOneImageJavascript {
position: absolute;
width: 100px;
height: 100px;
outline: 10px solid black;
}
JavaScript
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;
}
animate(
document.getElementById('challengeOneImageJavascript'),
"left","px",0,200,1000
);