How To Cross Fade Anything With JavaScript [JavaScript Fade Effect]

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.

XHTML

1

<div id="myElement">This text will toggle fade effects </div>

The JavaScript

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

functionfadeOut(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;}

}

functionfadeIn(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]

please wait...

Rating: 5.0/5 (6 votes cast)

How To Cross Fade Anything With JavaScript [JavaScript Fade Effect], 5.0 out of 5 based on 6 ratings