Skip to content

Instantly share code, notes, and snippets.

@louisbros
Last active December 16, 2015 15:29
Show Gist options
  • Save louisbros/5456222 to your computer and use it in GitHub Desktop.
Save louisbros/5456222 to your computer and use it in GitHub Desktop.
A simple JavaScript class for DOM object property animation without jQuery. - http://jsfiddle.net/louisbros/bkVQX/
function Animator() {
this._animated = [];
this.EASING = {
easeInOutCubic: function (e, f, a, h, g) {
if ((f /= g / 2) < 1) {
return h / 2 * f * f * f + a;
}
return h / 2 * ((f -= 2) * f * f + 2) + a;
},
easeOutBounce: function (e, f, a, h, g) {
if ((f /= g) < (1 / 2.75)) {
return h * (7.5625 * f * f) + a;
} else {
if (f < (2 / 2.75)) {
return h * (7.5625 * (f -= (1.5 / 2.75)) * f + 0.75) + a;
} else {
if (f < (2.5 / 2.75)) {
return h * (7.5625 * (f -= (2.25 / 2.75)) * f + 0.9375) + a;
} else {
return h * (7.5625 * (f -= (2.625 / 2.75)) * f + 0.984375) + a;
}
}
}
}
};
}
Animator.prototype = {
constructor: Animator,
animate: function (object, property, unit, from, to, duration, easing, callBack, iterationCallBack) {
var self = this;
if(from === to){
return;
}
for (var i = 0; i < this._animated.length; i++) {
if (this._animated[i].object === object && this._animated[i].property === property) {
return;
}
}
this._animated.push({
'object': object,
'property': property
});
object[property] = from + unit;
var start = new Date().getTime();
(function _animate() {
var now = new Date().getTime() - start;
var ease = self.EASING[easing](0, now, 0, 1, duration);
object[property] = (from + (to - from) * ease) + unit;
if (now < duration) {
if (iterationCallBack) {
iterationCallBack();
}
setTimeout(_animate, 1000 / 60);
} else {
object[property] = to + unit;
for (var i = 0; i < self._animated.length; i++) {
if (self._animated[i].object === object && self._animated[i].property === property) {
self._animated.splice(i, 1);
break;
}
}
if (callBack) {
callBack();
}
}
})();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment