Domanda

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?

È stato utile?

Soluzione

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

Altri suggerimenti

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top