jQuery: Tween from One Color to Another

From jQuery 1.2 onwards, the ability to tween (animate) from one color to another, in other words fade one color into a different color is as simple as inserting one line of code.

(In order to use this effect though, you will need to include the official Color Animations jQuery plugin which can be grabbed here.)

Technically all that the color animation is doing is it is making subtle CSS changes utilizing the jQuery.fx.step functionality to fire it along, but seeing as this all happens behind the scenes, all you really need to know are the CSS properties that you are allowed to manipulate in this manner…

…which are currently ‘backgroundColor’; ‘borderBottomColor’; ‘borderLeftColor’; ‘borderRightColor’; ‘borderTopColor’; ‘color’; ‘outlineColor’, just by the way.

In addition, colors can be specified as one of a pre-set range of named colors (e.g. blue, pink), or in rgb format (e.g. rgb(221,221,221)), or as hex (e.g. #cc6600), or finally as shorthand hex (e.g. #ddd).

Let’s for example say you wish to face a page’s background color from its current white, all the way through to blue and once that is done, tween the now blue background to it’s final pink stage.

To achieve this is really simple. What we are going to do is call the animate function which will be responsible for the color tween and when the first animate call is done, chain a second animate after the original to change the color to the final desired pink.

And here’s the jQuery magic that will do all of this for us:

$("body").animate( { backgroundColor: 'blue' }, 1000).animate( { backgroundColor: 'pink' }, 1000);

You’ll see in the above that all we do is specify the CSS property on which to act (this time it is BackgroundColor) and then specify how many milliseconds the animation needs to act for.

And that’s it. The magic of jQuery strikes again! :)

You might also enjoy:

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Technology & Code, Tutorials and tagged , color fade, colour, , tween. Bookmark the permalink.
    blog comments powered by Disqus