Tarana
Tarana

Reputation: 15

Fade In/Out text and Loop using jQuery

I am trying Jquery to Fade out text and then Fade in, and then loop this allover again. The loop part is not working. Wondering whats wrong?!?!

Here is the code:

JQUERY

<script>
    $("document").ready(function() {
        (function runIt() {
            $('#original').fadeOut('slow', function() {
                $('#original').fadeIn('slow').html('second');

                $(this).find('#original').html('first');

                runIt();

            });
        }());
    });
</script>

BODY

<p>
  <span id='original'>first</span>
</p>

Upvotes: 1

Views: 1988

Answers (2)

EternalHour
EternalHour

Reputation: 8621

It seems that I didn't understand the issue until I looked at it the second time. From what I can tell, you are trying to cycle between first and second? This will do that but it s not pretty since I'm not very adept with Javascript :X

Updated FIDDLE

(function runIt() {
        $('#original').fadeOut('slow', function(){
            $('#original').fadeIn('slow').html('second');
            $('#original').fadeOut('slow', function(){
                $('#original').fadeIn('slow').html('first');
    runIt();
            });
        });
    }());

Upvotes: 0

Aron Bordin
Aron Bordin

Reputation: 436

The problem is that you are trying to change the html to "first" before the "second" fadeIn completed. To run a Fade in/out loop, you need to fadeIn and fadeOut each slide completely. Use this sample bellow, with it, you will be able to add more scenes to the loop.

$("document").ready(function() {
    var texts = ["first", "second"];
    var i = 0;
    (function runIt() {
        i++;
        $('#original').fadeOut('slow', function() {
            $('#original').html(texts[i % texts.length]);
            $('#original').fadeIn('slow', function() {
                runIt()
            });
        });
    }());
});

You can test it here

Upvotes: 1

Related Questions