Last active
December 26, 2015 16:39
-
-
Save s4wny/7181179 to your computer and use it in GitHub Desktop.
Animate things without jQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Original code from http://gabrieleromanato.name/javascript-implementing-the-fadein-and-fadeout-methods-without-jquery/ | |
// Modified by Sony? aka Sawny | |
var Animator = { | |
// Uses "jQuery" style / standard style. So you can easly import easings from jQuery | |
// or other resources | |
// | |
// Format: | |
// percent | elapsed time | start value | end value | total duration | |
// x | t | b | c | d | |
easing: { | |
linear: function(x, t, b, c, d) { | |
return b+c*x; | |
}, | |
easeOutExpo: function (x, t, b, c, d) { | |
return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; | |
} | |
}, | |
animate: function(options) { | |
var start = new Date; | |
options.complete = options.complete || function() {}; | |
var id = setInterval(function() { | |
var timePassed = new Date - start | |
, progress = timePassed / options.duration; | |
if (progress > 1) { | |
progress = 1; | |
} | |
if(options.from > options.to) { | |
var delta = Animator.easing[options.easing](progress, timePassed, options.to, options.from, options.duration); | |
delta = options.from - delta; | |
} | |
else { | |
var delta = Animator.easing[options.easing](progress, timePassed, options.from, options.to, options.duration); | |
} | |
options.step(delta, options.element); | |
if (progress == 1) { | |
clearInterval(id); | |
delete options.element.quoAnimationID; | |
options.complete(); | |
} | |
}, options.delay || 10); | |
options.element.quoAnimationID = id; | |
} | |
}; | |
//-------------------------------- | |
// Example implemenation: | |
// | |
// this = querySelector(); | |
$$.fn.fadeIn = function(duration, easing, cb) { | |
Animator.animate({ | |
duration: duration, | |
element: this, | |
complete: cb, | |
easing: easing, | |
to: 1, | |
from: 0, | |
step: function(delta, element) { | |
element.css('opacity', delta); | |
} | |
}); | |
}; | |
$$.fn.fadeOut = function(duration, easing, cb) { | |
Animator.animate({ | |
duration: duration, | |
element: this, | |
complete: cb, | |
easing: easing, | |
to: 0, | |
from: 1 | |
step: function(delta, element) { | |
element.css('opacity', delta); | |
} | |
}); | |
}; | |
$$.fn.stopAnimation = function() { | |
clearInterval(this.quoAnimationID); | |
delete this.quoAnimationID; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment