0

I'm fairly new to JavaScript and JQuery. I've written a series of ends to a paragraph that I'm attempting to rotate with one another using a for loop. Although I am seeing the number of fades, the text isn't changing on my site.

Here's the code:

var paragraphs = ["foo", "bar", "foobar"];

var rotateText = function(){
    for(var i = 0; i < paragraphs.length; i++){
        $("#id").text(paragraphs[i]).fadeIn(2000).delay(2000).fadeOut(2000);
    }
};

rotateText();
2
  • Hint: fadeIn() (and its friends) isn't synchronous. Commented Feb 6, 2013 at 5:34
  • Could you please provide a jsfiddle example for it ? Commented Feb 6, 2013 at 5:50

2 Answers 2

0

There are a couple of problems here:

  1. .text does not respect the standard animation effects queue
  2. With the queue, the value of i will increment to 3 so it can't be used in callbacks.

This is solved by adding the text changing via a callback to .queue which itself is created via a function that uses the value of i as an argument so it can be used as-is locally. All told:

for (var i = 0; i < paragraphs.length; i++){
    $("#id").queue((function (i) {
        return function () {
            $(this).text(paragraphs[i]).dequeue();
        };
    })(i)
    ).fadeIn(2000).delay(2000).fadeOut(2000);
}

See it in action:

http://jsfiddle.net/ExplosionPIlls/gBxgQ/

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

2 Comments

Brilliant, thanks foe the explanation. I'll be sure to familiarize myself with the queue function. Thanks again!
Also note that you can use $.each to iterate over paragraphs and create a callback which is a separate closure that you can use the index with each time. You wouldn't have to create your own ad-hoc closure.
0

Try this :

this will print the text in circular fashion : foo - bar - foobar - foo - bar ..

var faderIndex = 0,

paragraphs = ["foo", "bar", "foobar"];
function nextFade() {
    $('#id').text(paragraphs[faderIndex]).fadeOut(1000, function() {
        faderIndex++;
        if (faderIndex >= paragraphs.length)
            faderIndex = 0;
        $('#id').text(paragraphs[faderIndex]).fadeIn(1000, nextFade);
    });
}
nextFade();

<div id="id"></div>

Demo : Working demo on JSFiddle

Also see : this SO question

1 Comment

Thanks for the help! Also, sorry for duplicating questions, but thanks for the reference.

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.