Skip to content

Instantly share code, notes, and snippets.

@oleksmarkh
Created March 19, 2016 12:48
Show Gist options
  • Save oleksmarkh/212e3b03de162886d41f to your computer and use it in GitHub Desktop.
Save oleksmarkh/212e3b03de162886d41f to your computer and use it in GitHub Desktop.
// <div id="block"></div>
// #block {
// position: relative;
// left: 200px;
// width: 40px;
// height: 40px;
// background-color: #456;
// }
function animate(el, props, duration) {
var timeDelta = 4;
var repetitions = Math.floor(duration / timeDelta) || 1;
var r = 0;
var computedStyles = getComputedStyle(el);
var initialStyles = {};
var deltaStyles = {};
for (var prop in props) {
initialStyles[prop] = parseFloat(computedStyles[prop]) || 0;
deltaStyles[prop] = (parseFloat(props[prop]) - initialStyles[prop]) / repetitions;
}
var move = function () {
r += 1;
for (var prop in props) {
el.style[prop] = initialStyles[prop] + deltaStyles[prop] * r + 'px';
}
if (r >= repetitions) {
clearInterval(interval);
}
};
var interval = setInterval(move, timeDelta);
}
animate(document.getElementById('block'), {
left: 100,
top: 20,
width: 100,
borderRadius: 5
}, 2000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment