JavaScript Cross FadeThis 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.

The Concept

CSS opacity property of the element to be faded is increased / decreased using JavaScript. To achieve the fade effect the fade functions are recursively called while introducing a time delay with native JavaScript setTimeout function.

VN:F [1.9.22_1171]
Rating: 5.0/5 (3 votes cast)
How To Cross Fade Anything With JavaScript [JavaScript Fade Effect], 5.0 out of 5 based on 3 ratings

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>