Skip to content

Instantly share code, notes, and snippets.

@Tythos
Created April 6, 2020 17:34
Show Gist options
  • Save Tythos/b292155bd826eb47412a8aa8b59ad183 to your computer and use it in GitHub Desktop.
Save Tythos/b292155bd826eb47412a8aa8b59ad183 to your computer and use it in GitHub Desktop.
Single-file JavaScript module: object-based animations for CSS-managed DOM manipulation
/* Object-based for DOM animation management of style properties.
*/
define(function(require, exports, module) {
function Animaniac() {
/* Initializes animation object with default parameters. Users will
typically assign the following properties before calling "start()":
* element (the relevant DOM element)
* properties (style property keys with 2-element initial/final values Array)
* callback (what to invoke when the transition has finished)
*/
this.handle = null;
this.started = new Date();
this.interval = 10; // ms
this._element = null;
this.properties = {};
this._duration = 1000;
this.callback = function() {};
return this;
};
Animaniac.prototype.element = function(element) {
this._element = element;
return this;
};
Animaniac.prototype.duration = function(dt_s) {
this._duration = dt_s * 1e3;
return this;
}
Animaniac.prototype.prop = function(prop, vals, suffix="") {
/*
*/
this.properties[prop] = [vals[0], vals[1], suffix];
return this;
};
Animaniac.prototype.start = function() {
/* Kicks off setInterval() call to update animation properties.
*/
this.started = new Date();
this.handle = setInterval(this.onInterval.bind(this), this.interval);
};
Animaniac.prototype.onInterval = function() {
/* Updates style properties via interpolation. Upon completion, final
properties are assigned and interval handle is cleared.
*/
let dt_ms = (new Date()) - this.started;
let pct = dt_ms / this._duration;
Object.keys(this.properties).forEach(function(key) {
let values = this.properties[key];
this._element.style[key] = (values[0] + pct * (values[1] - values[0])) + values[2];
}, this);
if (pct >= 1.0) {
Object.keys(this.properties).forEach(function(key) {
this._element.style[key] = this.properties[key][1] + this.properties[key][2];
}, this);
clearInterval(this.handle);
this.callback();
}
};
Object.assign(exports, {
"Animaniac": Animaniac,
"__uni__": "com.github.gist.tythos.animaniac",
"__semver__": "1.1.0",
"__author__": "code@tythos.net"
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment