Code: Select all
/**
* Fade the background-color of an object from one to another
* @param {Element} The target element
* @param {Array} The starting (Red, Green, Blue) as decimal 0-255
* @param {Array} The wanted (Red, Green, Blue) as decimal 0-255
* @param {Integer} The amount to adjust each color by at each frame (default to 3)
* @param {Integer} The number of milliseconds between each frame (default to 100)
* @return void
*/
function colorTransition(obj, start, end, increment, interval)
{
//Set some defaults
if (!increment) increment = 3;
if (!interval) interval = 100;
var R = 0, G = 1, B = 2;
//End recursion if all end values reached
if (start[R] == end[R] && start[G] == end[G] && start[B] == end[B]) return;
//Adjust values for each color
for (var color = R; color < B; color++) {
if (start[color] < end[color]) {
start[color] += parseInt(increment);
if (start[color] > end[color]) { start[color] = end[color]; } //Fix if out of bounds
}
else {
start[color] -= parseInt(increment);
if (start[color] < end[color]) { start[color] = end[color]; }
}
}
//Set the element's style to the requested color
var rgb = "rgb(" + start[R].toString() + "," + start[G].toString() + "," + start[B].toString() + ")";
obj.style.backgroundColor = rgb;
//Wait for the interval, then change the color again
window.setTimeout(function() { colorTransition(obj, start, end, parseInt(increment), parseInt(interval)); }, parseInt(interval));
}
Usage:
Code: Select all
<div id="foo">Some text</div>
<script type="text/javascript"><!--
//fade from white to black
colorTransition(document.getElementById("foo"), new Array(255,255,255), new Array(0,0,0));
//fade from red to blue
colorTransition(document.getElementById("foo"), new Array(255,0,0), new Array(0,0,255));
//fade from yellow to green, with a 50ms interval and a transition of 10 shades-per-frame
colorTransition(document.getElementById("foo"), new Array(255,255,0), new Array(0,255,0), 10, 50);
// --></script>