Вопрос

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?

Это было полезно?

Решение

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

Другие советы

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top