Search code examples
jquerystringdelayfadein

Fade In String Characters with JQuery?


Here is my code. For some reason the entire String fades in at one time instead of each individual character. My console.log shows the characters are being executed one by one. Why is the entire string fading in at one time? Shouldn't the statement within the for loop execute for each character?

<!DOCTYPE html>
<head>
  <script src="jquery.js" type="text/javascript" charset="utf-8"></script>
  <script>
    $(function() {
      string = " David";
      for(i = 0; i < string.length; i++) {
        $('#fadeIn').append(string[i]).delay(1000).hide().fadeIn(1000);
        console.log(string[i]);
      }
    });
  </script>
</head>
<body>
<div id="fadeIn" style="color: #000"></div>
</body>
</html>

Solution

  • To get the individual letters to fade in, they need to be DOM elements.

    $(function() {
      var string = " David";
      var q = jQuery.map(string.split(''), function (letter) {
        return $('<span>'+letter+'</span>');
      });
    
      var dest = $('#fadeIn');
    
      var c = 0;
      var i = setInterval(function () {
        q[c].appendTo(dest).hide().fadeIn(1000);
        c += 1;
        if (c >= q.length) clearInterval(i);
      }, 1000);
    
    });
    

    http://jsfiddle.net/bGsa3/5/