Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 868
Isaiah Bugarin Avatar asked Feb 20 '12 22:02

Isaiah Bugarin


People also ask

What are the steps to change the background color?

Select Start > Settings > Personalization > Colors, and then choose your own color, or let Windows pull an accent color from your background.

How do you change the background color on HTML?

How to Add Background Color in HTML. To add background color in HTML, use the CSS background-color property. Set it to the color name or code you want and place it inside a style attribute. Then add this style attribute to an HTML element, like a table, heading, div, or span tag.

How do I set two background colors in CSS?

CSS allows you to add multiple background images for an element, through the background-image property. The different background images are separated by commas, and the images are stacked on top of each other, where the first image is closest to the viewer.


4 Answers

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

like image 188
MarcinJuraszek Avatar answered Oct 18 '22 05:10

MarcinJuraszek


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/

like image 29
Adrien Schuler Avatar answered Oct 18 '22 05:10

Adrien Schuler


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()">.

like image 1
Alexander Pavlov Avatar answered Oct 18 '22 04:10

Alexander Pavlov


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

like image 1
mck Avatar answered Oct 18 '22 03:10

mck