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.

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.

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:

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:

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:

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.

Posted Tuesday, September 1st, 2009 · Back to Top

SPONSOR

Add Comment

77 Comments 47 Mentions

  1. Evan Jones Author Editor

    Haha that’s trippy!

    ·

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

    ·

  3. webmasterdubai Author Editor

    really nice work jquery really coool

    ·

  4. krike Author Editor

    Wow nice :D defenitly going to try this one out

    ·

  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.

    ·

  6. Loz Author Editor

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

    ·

  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

    ·

  8. Hitesh Author Editor

    IE 6 Crash on the demo page why?

    ·

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

      ·

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

    ·

  10. Jonathan Patterson Author Editor

    Very cool. Bookmarked for future reference!

    ·

  11. Lamin Barrow Author Editor

    Awesome! This is incredible. Thanks for the tutorial.

    ·

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

    ·

  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!

    ·

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

    ·

  15. wien Author Editor

    very helpful, thanks

    ·

  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

    ·

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

    ·

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

    ·

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

    ·

  20. Mat Author Editor

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

    Thank you!

    ·

  21. Birgit Author Editor

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

    ·

  22. babak Author Editor

    Thank you , its useful

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

    ·

  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.

    ·

  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.

    ·

  25. Dawid Author Editor

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

    ·

  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”

    ·

  27. geoffroy Author Editor

    does not work on safari… sigh…

    ·

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

    ·

  29. Drupal Consulting Author Editor

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

    ·

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

    ·

    • 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!

      ·

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

    ·

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

    ·

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

    ·

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

    ·

  35. jason Author Editor

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

    ·

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

    ·

    • shaman Author Editor

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

      ·

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

    ·

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

    ·

  39. Dejan web dizajner Author Editor

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

    ·

  40. HippoMegas Author Editor

    Wow simple y funcional, felicidades y gracias.

    ·

  41. sarath krishna Author Editor

    super…. luv u sam….

    ·

  42. bobby Author Editor

    very good, thanks for the insight

    ·

  43. Bradley Author Editor

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

    ·

  44. Kristine Author Editor

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

    ·

  45. Klaus Author Editor

    Very nice Effekt!

    Thank you for the tutorial.

    Best regards
    Klaus

    ·

  46. Surendra Author Editor

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

    ·

  47. seo optimizacija Author Editor

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

    ·

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

    ·

  49. Ebrahim Author Editor

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

    ·

  50. Ebrahim Author Editor

    not work in chrome :(

    ·

  51. Idris Author Editor

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

    ·

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

    ·

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

    ·

  54. Hrishikesh Author Editor

    Thanks man ! It’s really helpfull.

    ·

  55. Helen Author Editor

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

    ·

  56. wiyono Author Editor

    Really nice..Thank you

    ·

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

    ·

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

      ·

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

    ·

  59. 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 ;)

    ·

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

    ·

    • bryan Author Editor

      I’m interested!

      please do post

      ·

  61. 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);

    ·

    • 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);
      });

      ·

  62. 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 ;)

    ·

  63. Ramin Author Editor

    Really nice work sir

    ·

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

    ·

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

    ·

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

    ·

    • Vitaminico Author Editor

      i’ve the same question!

      ·

  67. sdss Author Editor

    no workie workie in safari safari

    ·

  68. Kristal Author Editor

    obviously like your web site but you have to check the spelling on quite a few of your posts. Many of them are rife with spelling issues and I to find it very troublesome to tell the reality nevertheless I’ll definitely come back again.

    ·

 

Build Internet by One Mighty Roar. Since 2008.