HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Animation that cycles through background colors

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
animationbackgroundcolorsthatthroughcycles

Problem

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 > 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;
}




Solution

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;
}




Context

StackExchange Code Review Q#77966, answer score: 3

Revisions (0)

No revisions yet.