It’s a Rainbow! – Color Changing Text and Backgrounds w/ jQuery

Here’s a quick and easy way to cycle between multiple colors smoothly.

Normally you would define the (background) color in the CSS and that would be the end of it. In this case we want to be able to adjust colors after the page has loaded, and not just once either – we’re aiming for continuous adjustments.

The lovely part about this whole thing is the small about of jQuery required to make it all happen.

What You Will Learn

  • How to generate a random RGB color value.
  • The process of animating/looping color changes via the jQuery Color Animations Plugin.
  • Some possible uses for continuous color swapping with backgrounds, texts, and images.

Generating Random Color Values

This is an important first step as it provides an endless supply of color values to transition to/from with a single line of jQuery.

var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';

This line makes a variable called hue that contains an RGB formatted color value that will be processed by the color animations plugin in later steps.

Transitioning Between Colors

Take the time to download the jQuery Color Animations Plugin – this will be responsible for the transitions between the colors we will be randomly generating.

After you have decided what will be changing color, we will make use of the color animation plugin. I have included ‘#div’ as a placeholder for your own element/feel free to adjust the timer to your needs.

$('#div').animate( { backgroundColor: hue }, 1000);

Completed jQuery

Now that we have a means of creating random colors and transitioning between them, let’s put it together in a function so we can loop it. We’ll call it spectrum(), it will be called initially when the page loads and then again from within the function.

This is what your final jQuery should look like:

$(document).ready(function() {

 spectrum();

 function spectrum(){
    var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
    $('#div').animate( { backgroundColor: hue }, 1000);
    spectrum();
 }

});

At this point you now are the proud creator of an ever-changing-color background, congratulations!

Possible Uses

Changing Background Color

While we did this in the above example, you could think about limiting the colors displayed to a certain shade (ie. blues, reds, etc.) by playing around with the ranges of the numbers generated for the hue variable.

If you wanted to change the background color of the body, the animation line would look like this:

$('body').animate( { backgroundColor: hue }, 1000);

Changing Text Color

This goes pretty much along the same lines as the background color blurb above, with a few minor changes.

If you wanted to change the text color of something with the class .colored, the animation line would look like this:

$('.colored').animate( { color: hue }, 1000);

Changing Image Color with PNG Frame

This is the route that I chose to go in the live demo.

Basically, I took a solid black PNG image and carved out the parts where I wanted the background to peek through. Then I applied the color animations to the background of the element containing this PNG frame. As a result the image appears to be changing color, pretty nifty right?

I would encourage you to download the files and have a look at the exact setup for further clarification.

  • Stumble It!
  • Bookmark It!
  • Tweet it!

About Sam Dunn

Sam is a partner at One Mighty Roar, a creative design and interactive media company from Massachusetts, USA. He can be found online at Vivalasam and Twitter.

 

Discussion

  1. Evan Jones

    September 1st, 2009 at 11:09 PM

    Haha that’s trippy!

  2. BornisNetwork

    September 2nd, 2009 at 12:15 AM

    Helpful post Sam,
    We use jquey and png mask to make an amazing Rainbow effect too. Check out it at our website entry page:
    http://BornisNetwork.com

    Thanks.
    .-= BornisNetwork´s last blog ..Hello world! =-.

  3. webmasterdubai

    September 2nd, 2009 at 3:22 AM

    really nice work jquery really coool

  4. krike

    September 2nd, 2009 at 4:20 AM

    Wow nice :D defenitly going to try this one out

  5. Loz

    September 2nd, 2009 at 10:12 AM

    What a coincidence – I’ve just been working on something similar: http://lauriehufford.com/nu/images.html

    My WIP code lets you specify an array of colors to cycle through.

    Another possible addition (though I havnt investigated closely), is to specify your png mask as a in the body, which lets you use background-img and color to have animated patterns & colors behind the mask.

    Could be fancy… could also be very over the top.

  6. Loz

    September 2nd, 2009 at 10:17 AM

    oops: “is to specify your png mask as a (img) tag in the body”

  7. Jimmy Ray

    September 2nd, 2009 at 5:58 PM

    pretty cool stuff, hope it doesn’t get annoying. I think I’m going to try and use it for my header, or at least on “jim” @ http://www.jimraymonds.com

  8. Hitesh

    September 3rd, 2009 at 3:02 AM

    IE 6 Crash on the demo page why?

  9. Ds lite Skin

    September 3rd, 2009 at 5:53 AM

    Excellent!it really nice work query really cool.
    .-= Ds lite Skin´s last undefined ..If you register your site for free at =-.

  10. Jonathan Patterson

    September 3rd, 2009 at 11:37 AM

    Very cool. Bookmarked for future reference!

  11. Lamin Barrow

    September 4th, 2009 at 2:48 AM

    Awesome! This is incredible. Thanks for the tutorial.

  12. Marcel

    September 5th, 2009 at 8:29 PM

    Thanks for the tip. I just felt kinda zeitgeist effect right now… I was thinking about it some days ago and now theres some items in my RSS feed also covering this.
    .-= Marcel´s last blog ..Ótica e Relojoaria Jade =-.

  13. corey

    September 6th, 2009 at 8:13 PM

    Nice effect, thanks! Can you tell me or quickly point me to a source to show me how you were able to cut out your layer so that the transparent background shows? I’m trying to achieve this with a text layer, a layer mask and a transparent background. thanks again!

  14. Ronny-André Bendiksen

    September 7th, 2009 at 5:19 PM

    I get the following error in the console when running the site:

    RangeError: Maximum call stack size exceeded.
    .-= Ronny-André Bendiksen´s last blog ..Oslo Grand Prix =-.

  15. wien

    September 8th, 2009 at 6:50 AM

    very helpful, thanks

  16. G Fournié

    September 9th, 2009 at 2:26 AM

    About the error, “Maximum call stack size exceeded”. It comes from the recursive call of the function “spectrum” which endlessly calls itself.

    That’s the big problem of this recursive call : at one time or another, if you let it run, it will exhaust your memory…

    Nice effect anyway but need more work to be really useable.

    Best regards

  17. PanJan

    September 16th, 2009 at 4:54 AM

    In IE8 recurrency does not occur (animation is displayed only once).
    Also there is a bug with the background. The color set by your nifty code, covers the part of the page with the image (overflows black background).
    Otherwise great effect (works like a charm on normal browser. Just needs some hacks for IE) :)

  18. insic

    September 17th, 2009 at 9:01 AM

    i got an error. ‘too much recursion’. how can we avoid this error?
    .-= insic´s last blog ..Ultimate Reference of Javascript Image Galleries and Slideshows =-.

  19. Andre

    September 18th, 2009 at 4:09 AM

    Very Good for changing Linkcolor in a Navigation on hover… but for everything else it’s to much in my opinion.
    .-= Andre´s last blog ..Das Beste der Woche – KW37 =-.

  20. Mat

    September 21st, 2009 at 4:31 PM

    Hello excellent tutorial!
    I need to use it through the “hover” ..
    How Could you do it?

    Thank you!

  21. Birgit

    November 7th, 2009 at 11:45 AM

    so simple, yet a handy and awesome effect… thanks for sharing!

  22. babak

    November 21st, 2009 at 2:44 AM

    Thank you , its useful

    babak zawari
    بابک زواری
    بابك زواري

  23. Andrew

    January 15th, 2010 at 10:44 AM

    Start.0 is null or not an object – IE7
    hmm, foxed me out. Any ideas? It works but that nasty little error in the IE tray “Error on Page” needs kicking into place.

  24. sheil

    February 24th, 2010 at 7:23 AM

    Hi, sam.

    I saw the demo. it really nice, but I want the color changes in body. what can i do to change the body color when i clicking one image. and it will continue other pages also.

  25. Dawid

    March 4th, 2010 at 11:42 AM

    Hmmm How to add to my user group in vbulletin this rainbow effect?

  26. Mat

    April 1st, 2010 at 10:45 AM

    Nice effect. Very simple to implement.

    Only problem is annoying js error detected in IE. Still works. Any idea how to sort this?

    Error is – “Object doesn’t support this property or method”

  27. geoffroy

    April 11th, 2010 at 1:49 PM

    does not work on safari… sigh…

  28. sairamflash@gmail.com

    April 26th, 2010 at 10:19 AM

    nice animation very colorful work jquery great , but doesn’t work in IE 6 , 7 that work but still in outside blinking.

    if u have any IE hacks ?

  29. Mauricio

    May 19th, 2010 at 6:33 PM

    Hi. Nice effect! I’ve applied over a jquery drop down menu wordpress plugin and it crashes in IE: the color animation stops and freeze the drop down effect.
    Maybe would you have some IE hacks? If you can, please look at giselakassoy.com.br/wordpress to see the bug.

    Regards!

  30. Drupal Consulting

    May 20th, 2010 at 8:28 PM

    @Geoffroy What version of Safari are you using? It seems to work fine in Safari 4

  31. Jan

    June 8th, 2010 at 7:47 AM

    Hey,

    you got an error in the code.

    It has to be
    $(‘#div’).animate( { backgroundColor: hue }, 1000, spectrum);

    So spectrum is called after the animation.

    Your code is adding infinitely animations to the objects until the stack is full..

  32. steve

    July 16th, 2010 at 9:23 AM

    :( it seems this ‘tutorial’ is rather crappy, based on the comments.
    It does seem to lend itself to the very sloppy code thats all over the internet, snapped up by newbie programmers and foisted on unsuspecting websites and users.

    while I hate the “Best of” or “roundup” type articles (500 Icon sources!) which are not better than a google search, this, I fear is worse .. I guess nobody has “time” to produce quality work

Join the Conversation!

Remember: Life's not all doom and gloom, so please keep it constructive. If we've made an error or missed something big, please let us know! Learning is revisions, after all.

CommentLuv is Enabled

 

Sponsors

Advertise on Build Internet!