Skip to content

Instantly share code, notes, and snippets.

@nicholasbs nicholasbs/fade.js
Created Jul 14, 2011

Embed
What would you like to do?
fadeIn and fadeOut functions that work on elements or ids (no libs required)
// TODO: IE support if I feel like it; make fade length directly configurable
(function() {
var DELTA = 0.06, // how much to change opacity each step
DURATION = 40; // how long in ms to pause between steps
function fadeFunc(direction, start, end) {
return function(el) {
el = typeof(el) == 'object' ? el : document.getElementById(el);
var step = function step() {
var opacity = el.style.opacity;
opacity = opacity === "" ? start : parseFloat(opacity);
var next = opacity + DELTA*direction;
if (Math.abs(next - end) < DELTA) {
el.style.opacity = end;
} else {
el.style.opacity = next;
setTimeout(step, DURATION);
}
}();
};
}
// generate fadeIn and fadeOut functions
window.fadeIn = window.fadeIn || fadeFunc(1, 0, 1);
window.fadeOut = window.fadeOut || fadeFunc(-1, 1, 0);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.