jQuery: typer

discussion: http://stackoverflow.com/questions/14714162/typing-text-effect-with-formatting-skip-html-tags-but-dont-remove helpers: http://jkirchartz.com/2011/10/jquery-type-effect-plugin.html https://github.com/jaz303/jquery-grab-bag/blob/master/javascripts/jquery.text-effects.js#L47 http://return-true.com/2012/01/html-compatible-jquery-typewriter/ http://stackoverflow.com/questions/8053683/display-a-sentence-one-character-at-a-time

by gianlucaguarini

HTML

<div id="foo"></div>

CSS

body{ 
  background-color: whiteSmoke; 
  font-size: 50px; 
  font-family: Arial;
 }
#foo { text-align:center }

JavaScript

$.fn.typer = function(text, options){
    options = $.extend({}, {
        char: ' ',
        delay: 1000,
        duration: 600,
        endless: true
    }, options || text);

    text = $.isPlainObject(text) ? options.text : text;

    var elem = $(this),
        isTag = false,
        c = 0;
    
    (function typetext(i) {
        var e = ({string:1, number:1}[typeof text] ? text : text[i]) + options.char,
            char = e.substr(c++, 1);

        if( char === '<' ){ isTag = true; }
        if( char === '>' ){ isTag = false; }
        elem.html(e.substr(0, c));
        if(c <= e.length){
            if( isTag ){
                typetext(i);
            } else {
                setTimeout(typetext, options.duration/10, i);
            }
        } else {
            c = 0;
            i++;
            
            if (i === text.length && !options.endless) {
                return;
            } else if (i === text.length) {
                i = 0;
            }
            setTimeout(typetext, options.delay, i);
        }
    })(0);
};

$('#foo').typer(['<i>Anyone</i> <u>is</u> <b>awesome</b>!', 'Foo bar.', 1337]);