Here, take a look at this code. => DEMO
I've tested it and it's working. This code also works in legacy browsers (such as IE8
etc).
First, we attach an event listener to our element (window
).
Then we define the function
(function fadeOut
) which will animate the opacity
property.
You have to pass options/parameters to our fadeOut
function.
Under the first (element)
parameter you have to specify the element
that is to be animated. The second (startLevel)
parameter is the level the animation should start
from. The third (endLevel)
parameter is the level the animation should stop
at. The forth (duration)
parameter is the duration of our animation. Finally the fifth (callback)
option is a callback, which means when our animation completes, you will get notified and also can pass some additional code.
Javascript
function attach(element,listener,ev,tf){
if(element.attachEvent) {
element.attachEvent("on"+listener,ev);
}else{
element.addEventListener(listener,ev,tf);
}
}
function fadeOut(element,startLevel,endLevel,duration,callback){
var fOInt;
op = startLevel;
fOInt = setInterval(function() {
if(op<=endLevel){
element.style.opacity = endLevel;
element.style.filter = "alpha(opacity = " + endLevel + ")";
clearInterval(fOInt);
if(typeof callback == 'function') callback(true);
}else{
op -= 0.1;
element.style.opacity = op;
element.style.filter = "alpha(opacity = " + op*100 + ")";
}
},duration);
}
attach(window,'load',function(){
fadeOut(document.getElementById('loader'),1,0,50,function(cb){
alert('The loader has faded out!')
});
},false);
HTML
<div class='loader' id='loader'></div>
CSS
.loader{
width:200px;
height:200px;
border:5px solid red;
background-color:brown;
opacity:1;
filter:alpha(opacity=100);
}