Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change background color every 30s (fade transition)

I would like someone to tell me what's the code for making a webpage background color (the background color of the whole page) to change (fade transition) every 30s to a given color variety. Is it simple? I guess css will make it easier?

I've searched over the internet and I only found gradients which is not what I want. Thank you in advance. I 've search codepen and jsfiffle for examples but no one had something that simple :/

Example: While browsing my page I want the background color to change from blue to green and then to orange and again blue and so on so on... :)

like image 779
Billef32 Avatar asked Jan 04 '15 14:01

Billef32


2 Answers

It's also possible to do this without any JavaScript at all, using CSS3 animations.

html,
body {
  height: 100%;
}

body {
  -webkit-animation: background 5s cubic-bezier(1,0,0,1) infinite;
  animation: background 5s cubic-bezier(1,0,0,1) infinite;  
}


@-webkit-keyframes background {
  0% { background-color: #f99; }
  33% { background-color: #9f9; }  
  67% { background-color: #99f; }
  100% { background-color: #f99; }
}

@keyframes background {
  0% { background-color: #f99; }
  33% { background-color: #9f9; }  
  67% { background-color: #99f; }
  100% { background-color: #f99; }
}
like image 196
ckuijjer Avatar answered Nov 30 '22 05:11

ckuijjer


Here's a jQuery approach, to complete Bogdan's answer, that takes 3 parameters: selector (example, ".container" or "div"), colors (an array of colors to switch in between) and time (controls how frequently the bgd color changes). I set it for 3 seconds (3000) so you can see it in action easier, but you can increase it to 30000 (30 seconds).

jQuery(function ($) {
    function changeColor(selector, colors, time) {
        /* Params:
         * selector: string,
         * colors: array of color strings,
         * every: integer (in mili-seconds)
         */
        var curCol = 0,
            timer = setInterval(function () {
                if (curCol === colors.length) curCol = 0;
                $(selector).css("background-color", colors[curCol]);
                curCol++;
            }, time);
    }
    $(window).load(function () {
        changeColor(".container", ["green", "yellow", "blue", "red"], 3000);
    });
});
.container {
    background-color: red;
    height:500px;
    -webkit-transition: background-color 0.5s ease-in-out;
    -moz-transition: background-color 0.5s ease-in-out;
    -o-transition: background-color 0.5s ease-in-out;
    -khtml-transition: background-color 0.5s ease-in-out;
    transition: background-color 0.5s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container"></div>
like image 25
Marventus Avatar answered Nov 30 '22 07:11

Marventus