Animation that cycles through background colors I am doing a background image animation using the function. It works, but I think I am doing more coding than what it requires. Can anyone please help me to minimize it?

Don't recommend the CSS animations, I am working for IE9.

Live



var call = function () {

var x = 0;

    return function () {
        x++;
        x = x &gt; 4 ? x=1 : x;
    $('#small').prop('class','').addClass('s'+x)
    .text(x)
    .animate({opacity: 0}, 3000, function() {
        call();
    });

        var y = x+1;

        $('#big').prop('class','').addClass('s'+y);

        $('#small').css({
            opacity:1
        })

    }

}();

call();
#big {
    width: 100px;
    height: 100px;
    position:relative;
    color:#fff;
  }

#small {
    position:absolute;
    left:0;
    top:0;
    width:100%;
    height:100%;
    color:#fff;
}


.s1,
.s5{
    opacity:1;
    background:gray;
}

.s2 {
    background:blue;
    opacity:1;
}

.s3 {
    background:yellow;
    opacity:1;
    color:#000;
}
.s4 {
    background:brown;
    opacity:1;
}
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"&gt;&lt;/script&gt;
&lt;div id="big" class="s2"&gt;
    &lt;div id="small" class="s1"&gt;&lt;/div&gt;
&lt;/div&gt;
The #big and #small divs are actually the same size.  Therefore, I would rename them to #outer and #inner.  You can use the same CSS rules for both.

There's no need to specify the opacity in the stylesheet, since the opacity will be controlled by the jQuery animation.

I'd renumber your classes starting from 0 so that you can take advantage of the modulo operator.  The JavaScript code just looks cleaner with %.

The function-returned-by-a-function would be easier to understand if you make the outer scope into an object.  It also deserves to have a better name than call.

All of the jQuery operations on $('#small') should be done in the same chain.

Clearing the class then calling addClass() is a roundabout way of just setting the class property.

function() { call(); } could just be simplified to call.



function ColorAnimation(speed) {
    var x = 0;
    var self = this;

    this.run = function() {
        x = (x + 1) % 4;
        var y = (x + 1) % 4;
        $('#outer').prop('class', 's' + y);
        $('#inner').prop('class', 's' + x)
                   .text(x + 1)
                   .css({ opacity: 1 })
                   .animate({opacity: 0}, speed, self.run);
    };
};

new ColorAnimation(3000).run();
#outer, #inner {
    width: 100px;
    height: 100px;
    position:relative;
    color:#fff;
}

.s0 {
    background:gray;
}
.s1 {
    background:blue;
}
.s2 {
    background:yellow;
    color:#000;
}
.s3 {
    background:brown;
}
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"&gt;&lt;/script&gt;
&lt;div id="outer" class="s2"&gt;
    &lt;div id="inner" class="s1"&gt;&lt;/div&gt;
&lt;/div&gt;