Skip to content

Instantly share code, notes, and snippets.

@nicholasbs
Created July 14, 2011 18:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicholasbs/1083067 to your computer and use it in GitHub Desktop.
Save nicholasbs/1083067 to your computer and use it in GitHub Desktop.
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