Pergunta

I'm building something that fades an array of texts in and out.

This is my work so far: http://jsfiddle.net/9j7U6/

I'm fading texts in and out, but the timing is off when I see it rendered.

$("#wantPlaceholder").fadeOut().html(wants[i]).fadeIn(2000).delay(3000);

What is the right way to do it?

Foi útil?

Solução

Use a callback. The callback will be called once the animation is done. The following code fades out the element. When it is fully faded out the HTML is modified and then it is faded in again.

$("#wantPlaceholder").fadeOut(1000, function(){
    $(this).html(wants[i]);
    $(this).fadeIn(2000);
});

Edit: Well, the looping could be done something like this:

(function myLoop(items, index) {
    index = (items.hasOwnProperty(index) ? index : 0);
    $("#wantPlaceholder").delay(3000).fadeOut(1000, function () {
        $(this).html(items[index]);
        $(this).fadeIn(1000, function () {
            myLoop(items, index + 1);
        });
    });
}(wants, 0));

Outras dicas

First the text need to be changed in the fadeOut() handler

function rotateWants() {
    var i = 0;
    var wantsLength = wants.length;

    function fade() {
        $("#wantPlaceholder").delay(5000).fadeOut(function () {
            $(this).html(wants[i]);
            i++;
            if (i >= wantsLength) {
                i = 0
            };
        }).fadeIn(2000, fade);
    }

    fade();
}

Demo: Fiddle

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top