Search code examples
javascriptjqueryanimationtimeout

Text animation: each and setTimeOut


I'm trying to animate some text. Different divs are displayed and hid one after another, so that it looks like a word is reduced to just a letter, and then completed again.

I need some sort of delay between the .each() cycles. I tried to use the setTimeOut() function, but I still see all the divs appearing and then disappearing together, instead of one by one.

function fadeInOut(element) {
  $(element).fadeIn("slow", function() {
    $(this).fadeOut("slow");
  })
}

function displayStepWords() {
  $('.stepWord').each(function(i) {
    setTimeout(fadeInOut(this), 5000 * i);
  })
}

displayStepWords();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="stepWord">BYE</div>
<div class="stepWord">BY</div>
<div class="stepWord">B</div>
<div class="stepWord">BY</div>
<div class="stepWord">BYE</div>


Solution

  • Unclear exactly what you are aiming at, but something like:

    function fadeInOut(element) {
      $(element).fadeIn("slow", function() {
        $(this).fadeOut("slow");
      })
    }
    
    function displayStepWords() {
      $('.stepWord').each(function(i) {
      var me = $(this);
        setTimeout( function(){fadeInOut(me);}, 1000 * i );
      })
    }
    
    displayStepWords();
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="stepWord">BYE</div>
    <div class="stepWord">BY</div>
    <div class="stepWord">B</div>
    <div class="stepWord">BY</div>
    <div class="stepWord">BYE</div>