Использование ( Демо )
fadeIn(element, 200); // ms
fadeIn("#element_id", 300);
fadeOut(element, 600, function() {
alert("fade finished");
});
Код
function fade(dom, current, target, duration, after) {
duration = duration || 600;
if (typeof dom === "string")
dom = document.getElementById(dom);
var start = +new Date();
var finish = start + duration;
var easing = function (pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
};
var interval = setInterval(function () {
var now = +new Date();
var pos = now > finish ? 1 : (now - start) / duration;
setOpacity(dom, interpolate(current, target, easing(pos)));
if (now > finish) {
clearInterval(interval);
after && after();
}
}, 13);
}
function fadeIn(dom, duration, after) {
fade(dom, 0, 1, duration, after);
}
function fadeOut(dom, duration, after) {
fade(dom, 1, 0, duration, after);
}
function setOpacity(obj, value) {
if (obj) {
obj.style.opacity = value;
obj.style.filter = 'alpha(opacity=' + value * 100 + ')';
obj.style.zoom = 1;
}
}
function interpolate(source, target, pos) {
return (source + (target - source) * pos).toFixed(3);
}