Flashing JavaScript Text

Here is a simple function that makes text in a tag fade into one colour slowly before quickly fading back into the original colour. If the background is the same colour as the text then the text will appear to fade in and out.

var color = 0;
var dir = 1;
function fade(){
  var quick = 50;
  var slow = 100;
  var el = document.getElementById('fadeInOut');
  if(!el){
    return;
  }
 
  if(dir){
    if (color < 255) {
      setTimeout(fade,slow);
      color += 10;
    }else{
      setTimeout(fade,quick);
      color = 255;
      dir = 0;
    }
  }else{
    if(color > 0){
      setTimeout(fade,quick);
      color -= 10;
    }else{
      setTimeout(fade,slow);
      color = 0;
      dir = 1;
    }
  }
  el.style.color = "rgb("+color+","+color+","+color+")";
}

This code works by using a group of setTimeout function calls to call the function in a loop. Each time the function is run some variables are set, the colour is changed and then the function is called again. Use it in the following way.

<body onload="fade();">
  <div id="fadeInOut" style="font-size:100px;">Fading Text</div>
</body>

So what would you use this for? Well if you where doing something intensive on a site you could use this trick to allow the user to see that things are going on before displaying the content that they requested.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
2 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.