Reputation: 493
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
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
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
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
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