Build Internet has a brand new theme, and that's only the beginning. Read the full story or hide this bar

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

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.

Wordpress.com stats not installed! Posted Tuesday, September 1st, 2009 / Back to Top

I this post. Tweet
SPONSOR

75 Comments 44 Mentions

  1. Evan Jones Author Editor

    Haha that’s trippy!

    September 1, 2009 · Reply

  2. BornisNetwork Author Editor

    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! =-.

    September 2, 2009 · Reply

  3. webmasterdubai Author Editor

    really nice work jquery really coool

    September 2, 2009 · Reply

  4. krike Author Editor

    Wow nice :D defenitly going to try this one out

    September 2, 2009 · Reply

  5. Loz Author Editor

    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.

    September 2, 2009 · Reply

  6. Loz Author Editor

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

    September 2, 2009 · Reply

  7. Jimmy Ray Author Editor

    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

    September 2, 2009 · Reply

  8. Hitesh Author Editor

    IE 6 Crash on the demo page why?

    September 3, 2009 · Reply

    • dave Author Editor

      You should always design with the intent to keep IE6 users out in the cold. Anyone still using IE6 does not deserve modern web technology. If work is forcing them to use IE6 they should get the IT department fired or find a new job.

      January 11, 2012 · Reply

  9. Ds lite Skin Author Editor

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

    September 3, 2009 · Reply

  10. Jonathan Patterson Author Editor

    Very cool. Bookmarked for future reference!

    September 3, 2009 · Reply

  11. Lamin Barrow Author Editor

    Awesome! This is incredible. Thanks for the tutorial.

    September 4, 2009 · Reply

  12. Marcel Author Editor

    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 =-.

    September 5, 2009 · Reply

  13. corey Author Editor

    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!

    September 6, 2009 · Reply

  14. Ronny-André Bendiksen Author Editor

    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 =-.

    September 7, 2009 · Reply

  15. wien Author Editor

    very helpful, thanks

    September 8, 2009 · Reply

  16. G Fournié Author Editor

    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

    September 9, 2009 · Reply

  17. PanJan Author Editor

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

    September 16, 2009 · Reply

  18. insic Author Editor

    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 =-.

    September 17, 2009 · Reply

  19. Andre Author Editor

    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 =-.

    September 18, 2009 · Reply

  20. Mat Author Editor

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

    Thank you!

    September 21, 2009 · Reply

  21. Birgit Author Editor

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

    November 7, 2009 · Reply

  22. babak Author Editor

    Thank you , its useful

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

    November 21, 2009 · Reply

  23. Andrew Author Editor

    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.

    January 15, 2010 · Reply

  24. sheil Author Editor

    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.

    February 24, 2010 · Reply

  25. Dawid Author Editor

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

    March 4, 2010 · Reply

  26. Mat Author Editor

    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”

    April 1, 2010 · Reply

  27. geoffroy Author Editor

    does not work on safari… sigh…

    April 11, 2010 · Reply

  28. sairamflash@gmail.com Author Editor

    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 ?

    April 26, 2010 · Reply

  29. Mauricio Author Editor

    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!

    May 19, 2010 · Reply

  30. Drupal Consulting Author Editor

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

    May 20, 2010 · Reply

  31. Jan Author Editor

    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..

    June 8, 2010 · Reply

    • Ben Author Editor

      Hey, just thought I’d say thanks for this comment, it sorted the too much recursion problem for me! It seems to have gone unnoticed by the people who complain but don’t actually read the comments looking for a solution.
      Thanks!

      June 1, 2012 · Reply

  32. steve Author Editor

    :( 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

    July 16, 2010 · Reply

  33. Toren Author Editor

    is it possible to use this in more than one div at a time on a page? i can only get it to work on one at a time.

    September 16, 2010 · Reply

  34. Marek Ventur Author Editor

    The whole crash-thing is more than understandable: The spectrum()-functions calls itself after each animation is queued, not after it has finished. This results in a very long queue even after a few seconds.

    The solution is quite easy: Move the recursive-spectrum()-call inside the ‘finished’-event-handler (have a look at the jQuery manual) of the animate function.

    September 29, 2010 · Reply

  35. Marek Ventur Author Editor

    You can find an improved version here: http://blog.marekventur.de/2010/10/tutorial-color-changing-liquid-effect-with-jquery/

    October 5, 2010 · Reply

  36. Phil Author Editor

    Great tutorial Sam! I implemented this technique with minor modifications on my website http://www.philmartinezdesign.com in the header. The outcome looks great!

    December 22, 2010 · Reply

  37. jason Author Editor

    Simply doesn’t work. I tried changing spectrum() to animate body background color and it does nothing.

    January 20, 2011 · Reply

  38. Jonny Kermode Author Editor

    Is there a way to slow the colour change down so it takes longer to make a transition between the colours?

    February 18, 2011 · Reply

    • shaman Author Editor

      Change animate( { color: hue }, 1000); to a higher number, say 5000.

      March 2, 2011 · Reply

  39. Roland Author Editor

    I could use some help if anyone from here can get me…..i want to do this color transition thing but instead of a color i want to use an image….so anyone have any idea how to do it?

    March 26, 2011 · Reply

  40. alex Author Editor

    Hey,
    I just want to take the code and make the body of the page change colour only, no png or anything. How do I do it – I’m a total novice…!

    thanks

    March 30, 2011 · Reply

  41. Dejan web dizajner Author Editor

    I saved this page a while ago. And now it’s time to use it! :)

    May 16, 2011 · Reply

  42. HippoMegas Author Editor

    Wow simple y funcional, felicidades y gracias.

    May 26, 2011 · Reply

  43. sarath krishna Author Editor

    super…. luv u sam….

    June 15, 2011 · Reply

  44. bobby Author Editor

    very good, thanks for the insight

    June 29, 2011 · Reply

  45. Bradley Author Editor

    Is there a way to do the same effect using gradients instead of solid colours?

    July 12, 2011 · Reply

  46. Kristine Author Editor

    Bradley – check this out for your gradients. http://css-tricks.com/5700-css3-gradients/

    July 12, 2011 · Reply

  47. Klaus Author Editor

    Very nice Effekt!

    Thank you for the tutorial.

    Best regards
    Klaus

    September 11, 2011 · Reply

  48. Surendra Author Editor

    how can i do it for every page refresh. I want to change the background color on every refresh.

    September 12, 2011 · Reply

  49. seo optimizacija Author Editor

    Great looking effect. Ie6 is crashing because it is very bad browser

    October 4, 2011 · Reply

  50. ponle Author Editor

    Guy,
    you tried coming up with the concept but you shoul have avoided recursion in the code.
    @all, the problem isnt with your browser, recursive calls will always chop your memory.
    Thats why the text book says avoid recursion especially when there are no conditions allowing you to break out of it.
    my 2 cents

    October 17, 2011 · Reply

  51. Ebrahim Author Editor

    thanks , it is very simple,
    but i need change img as content() or scr color how to this?

    October 28, 2011 · Reply

  52. Ebrahim Author Editor

    not work in chrome :(

    October 28, 2011 · Reply

  53. Idris Author Editor

    this is truly awesome stuff over here…thank you for sharing

    October 29, 2011 · Reply

  54. Mark Author Editor

    Looks great in Firefox but when I tried it in Internet Exploder– sorry Internet Explorer 8 on Windows 7 it threw an error dialog that said: “Out of memory at line 1279″. The animation still worked but obviously seeing an error like that might worry some website visitors – has anyone else seen this error?

    November 21, 2011 · Reply

  55. Jay Author Editor

    How can i use two images to overlap each other and fade their background colors? Pls suggest.

    As in this case the black background of one image will overlap the other image. I want two images with fading background overlaping each other without and black color hiding any part of the images.

    Pls help.

    Thnks

    December 5, 2011 · Reply

  56. Hrishikesh Author Editor

    Thanks man ! It’s really helpfull.

    December 17, 2011 · Reply

  57. Helen Author Editor

    Great script. I am having problems specifying the colours that can be used though. Can anyone give me any pointers?

    January 4, 2012 · Reply

  58. wiyono Author Editor

    Really nice..Thank you

    February 7, 2012 · Reply

  59. Angela Author Editor

    This is great and very useful, thanks!
    I do have one question though – when cycling through the spectrum, obviously some colors are darker than others. I was wondering if there is a way to set it to only cycle through the lighter end of the spectrum (cyan, yellow, violet, pink, etc.) rather than the full spectrum?
    thanks!
    Angela

    February 17, 2012 · Reply

    • Ben Author Editor

      It’s a bit late to reply, but just in case someone else find it useful, to get lighter colours, you can give the random values a minimum lower limit:

      Change these parts of the script:

      Math.floor(Math.random() * 256)

      to this:

      Math.floor(Math.random() * 255)+50

      This’ll only return numbers between 50 and 255. You can use different values for each R G and B component.

      June 1, 2012 · Reply

  60. Inspirational Quotes Author Editor

    It’s a Rainbow! – Color Changing Text and Backgrounds w/ jQuery | Build Internet I was suggested this website by my cousin. I am not sure whether this post is written by him as no one else know such detailed about my problem. You are amazing! Thanks! your article about It’s a Rainbow! – Color Changing Text and Backgrounds w/ jQuery | Build InternetBest Regards Cassetta

    March 26, 2012 · Reply

  61. Nico Author Editor

    Hey, great tut, but I heard there’s a bug on jQuery 1.8 and the property backgroundColor isn’t working, in fact I tried this code and it won’t do anything, any idea? Thanks ;)

    December 4, 2012 · Reply

  62. Nico Author Editor

    Now that I see this recursive call, I notice it’s too inefficient, because it calls itself god knows how many times per second, that consumes like 50% of the CPU’s power! Also it doesn’t free the memory from the function’s previous execution. There’s a better way using the setInterval function I’m trying, I’ll post it if somebody is interested =D

    December 4, 2012 · Reply

    • bryan Author Editor

      I’m interested!

      please do post

      December 9, 2012 · Reply

  63. bryan Author Editor

    i figured it out myself –

    a better way to loop is using the .animate jquery callback: (see after 1000 below i inserted a comma then “spectrum” which is the name of the function calling animate itself creating a loop)

    $(‘#element’).animate( { backgroundColor: hue }, 1000, spectrum);

    December 9, 2012 · Reply

    • Nico Author Editor

      yeah, that’s another way, in my function I needed to change 2 object’s color, so I made that and called that function every 5 secs with setInterval like this:

      $(document).ready(function() {
      setInterval(‘changeColors()’,5000);
      });

      December 9, 2012 · Reply

  64. Nico Author Editor

    It’s equally cpu consuming (check the task manager). I don’t know if it’s because the animate function isn’t hardware accelerated or what. I read css animations are better but not all browsers can handle them, I will have to read more about it ;)

    December 9, 2012 · Reply

  65. Ramin Author Editor

    Really nice work sir

    December 31, 2012 · Reply

  66. Hoang Author Editor

    change code:
    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(); // it stop jquery
    setTimeout(spectrum, 100); // new code
    }

    January 4, 2013 · Reply

  67. Kicoe Author Editor

    Hi,
    if I may, I’ve work on a plugin to do that :
    Hope it’ll help others who run into this thread…

    March 5, 2013 · Reply

  68. Paul Author Editor

    Hi ! Thanks a lot for this tutorial !
    But if I want to use this with specifics colors, not random ? How can I do ?

    April 15, 2013 · Reply

 

Join the Conversation

Back to Top / Comment RSS

2012 Build Internet. Created by One Mighty Roar. Icons by Komodo Media. Back to Top