Search code examples
csscolorsbackgroundcss-transitionsfade

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


Solution

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