Flashing JavaScript Text

27th January 2008

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.

  1. var color = 0;
  2. var dir = 1;
  3. function fade(){
  4. var quick = 50;
  5. var slow = 100;
  6. var el = document.getElementById('fadeInOut');
  7. if(!el){
  8. return;
  9. }
  10.  
  11. if(dir){
  12. if (color 0){
  13. setTimeout(fade,quick);
  14. color -= 10;
  15. }else{
  16. setTimeout(fade,slow);
  17. color = 0;
  18. dir = 1;
  19. }
  20. }
  21. el.style.color = "rgb("+color+","+color+","+color+")";
  22. }

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.

  1. <div id="fadeInOut" style="font-size:100px;">Fading Text</div>

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 This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.