Search code examples
javascriptjqueryinputdelaysettimeout

Display text in input field letter for letter with delay


I have this code snippet.

        <div class="content__img-txt">
          <a class="input-group">
          <input class="input-group-field" type="text">
          <div class="input-group-button">
            <input type="submit" class="button" value="&raquo;">
          </div>
        </div>

function showLetter (field, text, delay) {
        $(field).val(text.substring(0,1));
        for(var i = 2; i <= text.length; i++)
        {
            setTimeout(function(){
                $(field).val(text.substring(0,i));
            }, delay);
        }
    }
 showLetter (".input-group-field", "Show letter for letter with a delay of 1 second", 1000);

The console says : Uncaught TypeError: Cannot read property 'length' of undefined.

How can I display text in the input field but letter for letter and not the whole text at once, after the document has fully loaded?


Solution

  • Guess you need a closure to ensure setTimeout have their own loop, and you need to increase delay like following :

    function showLetter(field, text, delay) {
      $(field).val(text.substring(0, 1));
      for (var i = 2; i <= text.length; i++) {
        (function(i) {
           setTimeout(function() {
              $(field).val(text.substring(0, i));
           }, (delay=delay+100));
        })(i)
    
      }
    }
    showLetter(".input-group-field", "Show letter for letter with a delay of 1 second", 1000);
    

    DEMO