0

I'm trying to fadeIn an fadeOut items in the array to a div. I'm trying to make this work in a fadeIn fadeOut manner. So first item fades in stays for 3 secodns then fades back out, then the next item fadein, 3seocnds then fade out and so on..... why is wrong with my code. Check http://jsfiddle.net/Fpu2E/1/

2 Answers 2

3

The code you're using won't work for various reasons - having zero delay between calling fadeOut and fadeIn means you won't get the 3 second delay you're looking for between fading in and out, and that calling both functions lead to some strange effects with the jQuery effects queue.

A better option would be to use a recursive function together with delay to do this:

var div = $('div').hide(),
    news = ['news1', 'news2', 'news3'],
    count = 0;

function changeNews() {
    div.fadeIn(3000).delay(3000).fadeOut(3000, function() {
        changeNews();
    }).text(news[count++]);
}

changeNews();

A simple demo of this can be found here: http://jsfiddle.net/Fpu2E/4/

Sign up to request clarification or add additional context in comments.

Comments

2

This works...

var news = ['news1', 'news2', 'news3'],
    count = news.length,
    currentItem = 0;

showNextItem = function() {

    $('div').text(news[currentItem++]).fadeIn(3000, function() {
        var element = $(this);
        setTimeout(function() {
            element.fadeOut(1000, function() {
                if (currentItem < count) {
                    showNextItem();
                }
            });

        }, 3000);
    });

};

showNextItem();

jsFiddle.

1 Comment

Thanks alex +1, though i think Yi's approach is simpler.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.