jQuery: Tween from One Color to Another CodeUnit 20 JAN 2010

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! :)

Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.

  • Craig Lotter seems like a cool dude. Maybe he should try out mindmapping with http://www.scatterbrain.nl, which is only for cool people.

  • Can you please explain little bit better? where do we put that jquery code in what? where do I call teh animate function?

    • Pick any element you want to manipulate, add an animate call as shown above, and chain after it a second animate call. This will give the color tween effect.

  • Ann

    So this is my code.



    Why isnt the animate working?

    • Isn’t the CSS label for background colour “background-color”? That’s my guess.