This is one sure question that every budding web developer would have in his mind. Today I am going to explain how to achieve cross fade effect using JavaScript and CSS opacity property. As always lets use pure 100% home grown JavaScript. No frameworks are used.
Demo
The HTML
Its necessary for the element to have an id to identify for the cross fade function.
<div id="myElement">This text will toggle fade effects </div>
The JavaScript
function fadeOut(id,val){
if(isNaN(val)){ val = 9;}
document.getElementById(id).style.opacity='0.'+val;
//For IE
document.getElementById(id).style.filter='alpha(opacity='+val+'0)';
if(val>0){
val--;
setTimeout('fadeOut("'+id+'",'+val+')',90);
}else{return;}
}
function fadeIn(id,val){
if(isNaN(val)){ val = 0;}
document.getElementById(id).style.opacity='0.'+val;
//For IE
document.getElementById(id).style.filter='alpha(opacity='+val+'0)';
if(val<9){
val++;
setTimeout('fadeIn("'+id+'",'+val+')',90);
}else{return;}
}
You might have noticed two functions fadeOut and fadeIn. The function names define what they do.