Skip to content Skip to sidebar Skip to footer

Fade Background Color Change Animation Lags And Slows Down

I'm trying to change the background color and a series of images through cross-fade via javascript. In first 3-4 loops both are synchronized (each color in 2 seconds and each image

Solution 1:

Removed the setInterval function and put all your code in one place, so now the animation and text are synchronized:

HTML:

<div class="container">
    <div class="back"></div>
    <div class="main"></div>
</div>

CSS:

.container {
    position:absolute;
    top:0px;
    left:50%;
    margin-left:-75px;
    width:130px;
    height:130px;
    border:10px solid yellow;
}
.back {
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
}
.main {
    position:relative;
    text-align:center;
    color:white;
    background-color:transparent;
}

JS:

$(function () {
    var colors = ['black', 'red', 'blue', 'green', 'black'];
    var i = 0;
    var cont = $('div.container');
    var back = $('div.back');
    var main = $('div.main');
    back.css('opacity', 1);
    back.css('backgroundColor', colors[0]); // start color , fades out
    cont.css('backgroundColor', colors[1]); // target color
    anim();

    function anim() {
        if (i == colors.length - 1) {
            i=0;
            //return; // repeat ad infinitum
        }
        main.text(colors[i+1]);
        var top = (cont.height() - main.height())/2 |0;
        main.css('top', top + 'px'); //center text vertically
        back.css({
            backgroundColor: colors[i],
            opacity: 1
        });
        cont.css({
            backgroundColor: colors[i+1]
        });
        i++;
        back.stop().animate({
            opacity: 0
        }, 2000, anim);
    }
});

http://jsfiddle.net/TytSZ/10/
http://jsfiddle.net/TytSZ/12/ (modified algorithm with transparent .png images)


Post a Comment for "Fade Background Color Change Animation Lags And Slows Down"