How To Create An Opacity Fade()? ( Improvement Over Jquery)
I'm not using JQuery but I know they have functions to do this. I know how to do this in JQuery but I want a pure js solution. How can I time vary the CSS opacity setting? A unix
Solution 1:
Here's an animation function using setTimeout. You can see it work here: http://jsfiddle.net/jfriend00/GcxdG/.
functiontoggleOpacity(id) {
var el = document.getElementById(id);
if (el.style.opacity == 1) {
fadeObject(el, 1, 0, 2000)
} else {
fadeObject(el, 0, 1, 2000)
}
}
functionfadeObject(el, start, end, duration) {
var range = end - start;
var goingUp = end > start;
var steps = duration / 20; // arbitrarily picked 20ms for each stepvar increment = range / steps;
var current = start;
var more = true;
functionnext() {
current = current + increment;
if (goingUp) {
if (current > end) {
current = end;
more = false;
}
} else {
if (current < end) {
current = end;
more = false;
}
}
el.style.opacity = current;
if (more) {
setTimeout(next, 20);
}
}
next();
}
Note: this is not yet adapted for older IE versions which don't respond to the opacity
style and need to have their opacity set via an IE-specific filter
setting.
Solution 2:
for (var i = 1; i < 100; i += 1) { // change the += 1 for different smoothness
(function(i) {
setTimeout(function() {
el.style.opacity = (100 - i) * 0.01;
}, i * 10);
})(i);
}
Post a Comment for "How To Create An Opacity Fade()? ( Improvement Over Jquery)"