Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typewriter Effect with jQuery

Tags:

jquery

Edit: I didn't really ask all the questions I should have asked in my original question. To help make this easier for people looking for a similar answer, this is what the question ended up being:

How do I make a typewriter effect with a blinking cursor that pauses at the end of the statement, erases the statement, and writes a new one?

Check out Yoshi's answer below. It does exactly that...

like image 681
blahblahAMYblah Avatar asked Nov 10 '12 18:11

blahblahAMYblah


People also ask

How do I create a CSS typewriter effect for my website?

The Typewriter Effect Is Easy to CreateThe typewriter animation is going to reveal our text element by changing its width from 0 to 100%, step by step, using the CSS steps() function. A blink animation is going to animate the cursor that “types out” the text.


2 Answers

demo: http://jsbin.com/araget/5/

/*** Plugin ***/

(function($) {
  // writes the string
  //
  // @param jQuery $target
  // @param String str
  // @param Numeric cursor
  // @param Numeric delay
  // @param Function cb
  // @return void
  function typeString($target, str, cursor, delay, cb) {
    $target.html(function(_, html) {
      return html + str[cursor];
    });

    if (cursor < str.length - 1) {
      setTimeout(function() {
        typeString($target, str, cursor + 1, delay, cb);
      }, delay);
    } else {
      cb();
    }
  }

  // clears the string
  //
  // @param jQuery $target
  // @param Numeric delay
  // @param Function cb
  // @return void
  function deleteString($target, delay, cb) {
    var length;

    $target.html(function(_, html) {
      length = html.length;
      return html.substr(0, length - 1);
    });

    if (length > 1) {
      setTimeout(function() {
        deleteString($target, delay, cb);
      }, delay);
    } else {
      cb();
    }
  }

  // jQuery hook
  $.fn.extend({
    teletype: function(opts) {
      var settings = $.extend({}, $.teletype.defaults, opts);

      return $(this).each(function() {
        (function loop($tar, idx) {
          // type
          typeString($tar, settings.text[idx], 0, settings.delay, function() {
            // delete
            setTimeout(function() {
              deleteString($tar, settings.delay, function() {
                loop($tar, (idx + 1) % settings.text.length);
              });
            }, settings.pause);
          });

        }($(this), 0));
      });
    }
  });

  // plugin defaults  
  $.extend({
    teletype: {
      defaults: {
        delay: 100,
        pause: 5000,
        text: []
      }
    }
  });
}(jQuery));


/*** init ***/

$('#target').teletype({
  text: [
    'Lorem ipsum dolor sit amet, consetetur sadipscing elitr,',
    'sed diam nonumy eirmod tempor invidunt ut labore et dolore',
    'magna aliquyam erat, sed diam voluptua. At vero eos et',
    'accusam et justo duo dolores et ea rebum. Stet clita kasd',
    'gubergren, no sea takimata sanctus est Lorem ipsum dolor sit',
    'amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr,',
    'sed diam nonumy eirmod tempor invidunt ut labore et dolore',
    'magna aliquyam erat, sed diam voluptua. At vero eos et accusam',
    'et justo duo dolores et ea rebum. Stet clita kasd gubergren,',
    'no sea takimata sanctus est Lorem ipsum dolor sit amet.'
  ]
});

$('#cursor').teletype({
  text: ['_', ' '],
  delay: 0,
  pause: 500
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<span id="target"></span>
<span id="cursor"></span>
<!-- used for the blinking cursor effect -->

plugin:

(function ($) {
  // writes the string
  //
  // @param jQuery $target
  // @param String str
  // @param Numeric cursor
  // @param Numeric delay
  // @param Function cb
  // @return void
  function typeString($target, str, cursor, delay, cb) {
    $target.html(function (_, html) {
      return html + str[cursor];
    });
    
    if (cursor < str.length - 1) {
      setTimeout(function () {
        typeString($target, str, cursor + 1, delay, cb);
      }, delay);
    }
    else {
      cb();
    }
  }
  
  // clears the string
  //
  // @param jQuery $target
  // @param Numeric delay
  // @param Function cb
  // @return void
  function deleteString($target, delay, cb) {
    var length;
    
    $target.html(function (_, html) {
      length = html.length;
      return html.substr(0, length - 1);
    });
    
    if (length > 1) {
      setTimeout(function () {
        deleteString($target, delay, cb);
      }, delay);
    }
    else {
      cb();
    }
  }

  // jQuery hook
  $.fn.extend({
    teletype: function (opts) {
      var settings = $.extend({}, $.teletype.defaults, opts);
      
      return $(this).each(function () {
        (function loop($tar, idx) {
          // type
          typeString($tar, settings.text[idx], 0, settings.delay, function () {
            // delete
            setTimeout(function () {
              deleteString($tar, settings.delay, function () {
                loop($tar, (idx + 1) % settings.text.length);
              });
            }, settings.pause);
          });
        
        }($(this), 0));
      });
    }
  });

  // plugin defaults  
  $.extend({
    teletype: {
      defaults: {
        delay: 100,
        pause: 5000,
        text: []
      }
    }
  });
}(jQuery));

html:

<span id="target"></span>
<span id="cursor"></span> <!-- used for the blinking cursor effect -->

init:

$('#target').teletype({
  text: [
    'Lorem ipsum dolor sit amet, consetetur sadipscing elitr,',
    'sed diam nonumy eirmod tempor invidunt ut labore et dolore',
    'magna aliquyam erat, sed diam voluptua. At vero eos et',
    'accusam et justo duo dolores et ea rebum. Stet clita kasd',
    'gubergren, no sea takimata sanctus est Lorem ipsum dolor sit',
    'amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr,',
    'sed diam nonumy eirmod tempor invidunt ut labore et dolore',
    'magna aliquyam erat, sed diam voluptua. At vero eos et accusam',
    'et justo duo dolores et ea rebum. Stet clita kasd gubergren,',
    'no sea takimata sanctus est Lorem ipsum dolor sit amet.'
  ]
});

$('#cursor').teletype({
  text: ['_', ' '],
  delay: 0,
  pause: 500
});
like image 142
Yoshi Avatar answered Nov 15 '22 19:11

Yoshi


Added a simple function at the end, and a few variables in between...

Fiddle

var where, when; //added

$.fn.teletype = function(opts){
    var $this = this,
        defaults = {
            animDelay: 50
        },
        settings = $.extend(defaults, opts);

    var letters = settings.text.length; //added

    where = '#' + $($this).attr('id'); //added
    when = settings.animDelay; //added

    $.each(settings.text, function(i, letter){
        setTimeout(function(){
            $this.html($this.html() + letter);

            if( $($this).html().length == letters ){ reverse(); } // Added to trigger reversing function

        }, settings.animDelay * i);
    });
};

$(function(){
    $('#container').teletype({
        animDelay: 100,
        text: 'Now is the time for all good men to come to the aid of their country...'
    });
});


// Added Reversing Function

    function reverse(){

        if ($(where).html().length > 0){          
            x = $(where).html().length - 1;
            y = $(where).html().substr(0, x);
            $(where).html(y);
            setTimeout(reverse , when);
        }else{
            console.log('Reverse Complete');
            clearTimeout(reverse);
        }
    }
like image 29
VIDesignz Avatar answered Nov 15 '22 20:11

VIDesignz