Search code examples
jqueryloopsfadeinfadeout

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>

Solution

  • 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