Isaiah Bugarin
Isaiah Bugarin

Reputation: 493

How to make background gradually change colors?

I'm trying to make a web page where the background color of an image gradually changes colors. I know how to change the background color of something in Javascript, but I don't know how to "animate" it so to speak (without using Flash).

Upvotes: 5

Views: 17470

Answers (4)

Adrien Schuler
Adrien Schuler

Reputation: 2425

Here is an example on how to animate the body tag background :

function animateBg(i) {
    document.body.style.backgroundColor = 'hsl(' + i + ', 100%, 50%)';

    setTimeout(function() {
        animateBg(++i)
    }, i);
}
animateBg(0);​

Keep in mind that hsl isn't crossbrowser, you can also do the trick with hex/rgb colors.

Jsfiddle link : http://jsfiddle.net/euthg/

Upvotes: 3

mck
mck

Reputation: 2190

I would try using a JQuery color plugin. Look at the examples here (click on Demo), they seem to do exactly what you describe.

Upvotes: 1

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

You can use CSS transitions to get that effect. Just add that css code into the element that is changed from js:

-webkit-transition: all 1s ease-in-out;
-moz-transition: all 1s ease-in-out;
-o-transition: all 1s ease-in-out;
-ms-transition: all 1s ease-in-out;
transition: all 1s ease-in-out;

With that on css each time any style value is being changed that change is animated from current to new value by 1s.

It works only on modern browsers. See an example: click

Upvotes: 10

Alexander Pavlov
Alexander Pavlov

Reputation: 32286

You might want to use the setTimeout() function:

function animateBg()
{
  myElement.style.backgroundColor = someNewValue;
  setTimeout(animateBg, 20); // 20 milliseconds
}

and invoke animateBg() in your body's onload handler. E.g., <body onload="animateBg()">.

Upvotes: 1

Related Questions