Javscript function - fadeText()

Unlike fading opacity, the following snippet fades the color of the text using the method of color blend. It's useful when you don't want the background-color fading with the text.

Color blend

First, we need to look at a javascript function for color blend. This function return a color value between the 2 colors in a certain ratio.

function Blend(a, b, alpha) {
  var aa = [
        parseInt('0x' + a.substring(1, 3)), 
        parseInt('0x' + a.substring(3, 5)), 
        parseInt('0x' + a.substring(5, 7))
    ];
  var bb = [
        parseInt('0x' + b.substring(1, 3)), 
        parseInt('0x' + b.substring(3, 5)), 
        parseInt('0x' + b.substring(5, 7))
    ];
  r = '0' + Math.round(aa[0] + (bb[0] - aa[0])*alpha).toString(16);
  g = '0' + Math.round(aa[1] + (bb[1] - aa[1])*alpha).toString(16);
  b = '0' + Math.round(aa[2] + (bb[2] - aa[2])*alpha).toString(16);
  return '#'
        + r.substring(r.length - 2)
        + g.substring(g.length - 2)
        + b.substring(b.length - 2);

Fade text

Here is the function of fadeText using color blend.

function fadeText(cl1,cl2,elm){
    var t = [];
    var steps = 100; // you can customize
    var delay = 3000; // you can customize
    for (var i = 0; i<steps; i++) {
      (function(j) {
           t[j] = setTimeout(function() {  
            var a  = j/steps;
            var color = Blend(cl1,cl2,a);     
            elm.style.color = color;           
           }, j*delay/steps);                    
      })(i);  
    }
    return t;
}

In the above function, t is an array to store the ids of setTimeout. The functon returns the ids of the setTimeout so that they can be stopped by other functions.

To stop the fading. use the following function.

function stopfade(t){    
     for (i in t) {
        clearTimeout(t[i]);
     }       
}

Normally, stopfade function goes before the fadeText. Use the snippet as follow,

var T = [];
var cl1 = "#ffffff";
var cl2 = "#c00000";
var elm = document.getElementById("note");
stopfade(T);
T  = fadeText(cl1,cl2,elm);

This is testing text.

Social Bookmark if it is useful.