Categories:

Fading in text using the DOM

Fading backgrounds may no longer be the rage, but fading text in all likelihood will prove a lot more enduring. Below we will do with scripting what Java and Flash have "been there done that" with- fade text gradually into view

Example:

General idea

Let's take a quick trip down memory lane. To change the document's background color, the code to use is:

document.bgColor="#000000" //change color to black 

Oh yeah, haven't seen that in a long time. A background fade is created merely by incessantly calling this code to gradually change the color from one extreme to another.

Moving on, dynamically changing the text's color was never historically possible until now:

document.getElementById("test").style.color="#008000" //change color to green 

Here a textual element with ID "test" has its color transformed to green.

Fading text technique

Believe it or not, the time is ripe to tackle the main subject. What we want is a script that continuously changes the text color, so as to achieve that nifty fade effect. The trickiest part of it in our opinion is in fact figuring out the hexadecimal equivalent of color values!

<script language="JavaScript1.2">
hex=255 // Initial color value.

function fadetext(){ 
if(hex>0) { //If color is not black yet
hex-=11; // increase color darkness
document.getElementById("sample").style.color="rgb("+hex+","+hex+","+hex+")";
setTimeout("fadetext()",20); 
}
else
hex=255 //reset hex value
}

</script>

<div id="sample" style="width:100%"><h3>John slowly faded into view</h3></div>
<button onClick="fadetext()">Fade Text</button>

Demo:

John slowly faded into view

Notice how we can use rgb values to denote the color, which comes in handy with the application at hand. By changing the value from 255 slowly to 0, we have a fade from white to black!

-Fading colors other than black

Sometimes you may wish to fade from white to a color other than black. A popular one is to blue, useful in fading in a text link, for example. Determining the hex equivalent of colors is definitely not a job intended for us humans. I suggest using a graphics program such as Paint Shop Pro, and launching the color palette for the task. Drag around the mouse to get the various shades of any color, plus their hex number.