ColorChanger is a custom JavaScript object that can transition any style property of an HTML entity from any one color to another by calculating intermediate colors.
Articles and downloads sponsored by:
Thanks! Amazon commissions help me pay for textbooks.
A
ColorChanger object is created for a specific HTML entity and
style property. Let's say that
we have the following HTML tag:
1 <div id="TestDiv" style="background-color: #B81818;">
2 Lorem ipsum dolor sit amet, consectetuer adipiscing elit...
3 </div>
We want to fade it's background color to another arbitrary color. In JavaScript, an HTML entity's background color is controlled by the
[HTML entity].style.backgroundColor property, so the
style property that we want to change is the
backgroundColor
property. The HTML entity (the
div tag) that we want to change has the ID "TestDiv". Thus, the
ColorChanger object should be
created as follows:
1 var cc = new ColorChanger("TestDiv", "backgroundColor", "B81818");
The first parameter to the constructor is the ID of the HTML entity, the second is the
style property we want to fade the color of,
and the third and final parameter is the initial color of the entity.
Now, to cause a color change, we call the
ChangeColor function like this:
1 cc.ChangeColor("FFFFFF", 10, 65);
The first parameter to the
ChangeColor method is the hex code for the new color. The second is the number of frames to use in the color change
animation. The third is the time delay between frames in milliseconds.
Thus, the total animation time is the number of frames multiplied by the delay between frames. To achieve a higher quality animation, use a larger
number of frames with a smaller delay between each. However, when changing colors of elements with a large surface area, it helps to decrease the
number of frames to ensure that the animation is not too processor-intensive for older browsers to render.
While each animation takes a set amount of time, the
ColorChanger object can be interrupted at any time and seamlessly 'redirected'. If the color
change animation is in progress and the
ChangeColor method is called again, the old animation is stopped and the new animation is started
from the current point without interruption.
The
colorchanger.js can be downloaded here. Simply include this code in your pages to use the
ColorChanger object.