Skip to content

Instantly share code, notes, and snippets.

@meiamsome
Last active June 19, 2016 17:03
Show Gist options
  • Save meiamsome/93ef2cb5c7b6bb3d12eba0b818af2065 to your computer and use it in GitHub Desktop.
Save meiamsome/93ef2cb5c7b6bb3d12eba0b818af2065 to your computer and use it in GitHub Desktop.
Allows creation of a value that can be transitioned with CSS 3 transitions.
// Create a number that takes 100s to transition after a 1s delay with an ease-in-out
test_number = new transitioned_variable(0, "100s", "ease-in-out", "1s");
// Create a color with a 100s transition, and no set easing or delay
test_color = new transitioned_variable("#000", "100s", undefined, undefined, transitioned_variable.TYPE_COLOR);
// Bouncy transition
test_bounce = new transitioned_variable(0, "5s", "ease-in-out");
// After a second, alter our values
setTimeout(function(){
test_number.set(100);
test_color.set("#fb1");
test_bounce.set(10);
}, 1000);
// Log the value every half of a second
setInterval(function() {
console.log(test_number.value(), test_color.value(), test_bounce.value());
}, 500);
// When our bounce ends, send it the other way!
test_bounce.transitionEnd(function() {
test_bounce.set(10 - test_bounce.value());
});
transitioned_variable = (function() {
function transitioned_variable(initial_value, duration, easing, delay, type) {
this.init(initial_value, duration, easing, delay, type);
}
transitioned_variable.TYPE_NUMBER = 0;
transitioned_variable.TYPE_COLOR = 1;
transitioned_variable.prototype = {
element: null,
duration: null,
easing: null,
delay: null,
type: null,
style: "",
transition_string: "",
init: function(initial_value, duration, easing, delay, type) {
this.element = document.createElement("span");
document.body.appendChild(this.element);
this.duration = duration || "1s";
this.easing = easing || "linear";
this.delay = delay || "0s";
this.type = type || this.TYPE_NUMBER;
this.style = this.type == this.TYPE_NUMBER ? "width" : "color";
this.transition_string = this.style + " " + this.duration + " " + this.easing + " " + this.delay;
this.element.style[this.style] = initial_value + (this.type == this.TYPE_NUMBER ? "px" : "");
this.element.style["transition"] = this.transition_string;
},
set: function(value){
this.element.style[this.style] = value + (this.type == this.TYPE_NUMBER ? "px" : "");
},
value: function(){
var value = window.getComputedStyle(this.element)[this.style];
if(this.type == this.TYPE_NUMBER) {
return parseFloat(value);
}
return value;
},
addEventListener: function() {
this.element.addEventListener.apply(this.element, arguments);
},
transitionEnd: function(func) {
this.addEventListener("transitionend", func);
}
};
return (window.transitioned_variable = transitioned_variable);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment