Search code examples
jqueryvariablesjquery-animatedelay

jquery animate() color multiple times, every 5 seconds, then loop/restart


I am new to coding my own jQuery. I've loaded jQuery and the jQuery color plugin and have managed a simple color animate after a 5 second delay, with a 1 second transition:

$("h1").delay(5000).animate({
    color: "blue"
}, 1000 );

What I am trying to do next is change the color again and again, every 5 seconds (blue, green, red, pink, orange) and then have that cycle continue over and over without stopping.

I found this post that was somewhat helpful in showing that the colors can be set in a variable but I'm not sure where to go from there and have the cycle start over when it's done.

Any help and/or links would be appreciated.


Solution

  • Try this:

    Fiddle

    var c = 0;
    setInterval(function () {
        var colors = ['blue', 'green', 'red', 'olive', 'yellow']
        if (c > colors.length - 1) c = 0;
        $("h1").animate({
            color: colors[c++]
        }, 1000);
    }, 5000);
    

    CSS solution for this would be:

    Fiddle

    h1 {
        animation: colorChanger 60s infinite;
        -moz-animation: colorChanger 60s infinite;
        -webkit-animation: colorChanger 60s infinite;
    }
    
    @-moz-keyframes colorChanger {
        from {
            color: blue;
            animation-duration: 1s;
        }
        20% {
            color: green;
            animation-duration: 1s;
        }
        40% {
            color: red;
            animation-duration: 1s;
        }
        60% {
            color: olive;
            animation-duration: 1s;
        }
        80% {
            color: yellow;
            animation-duration: 1s;
        }
        to {
            color: brown;
            animation-duration: 1s;
        }
    }
    @-webkit-keyframes colorChanger {
        from {
            color: blue;
            animation-duration: 1s;
        }
        20% {
            color: green;
            animation-duration: 1s;
        }
        40% {
            color: red;
            animation-duration: 1s;
        }
        60% {
            color: olive;
            animation-duration: 1s;
        }
        80% {
            color: yellow;
            animation-duration: 1s;
        }
        to {
            color: brown;
            animation-duration: 1s;
        }
    }