Skip to content

Instantly share code, notes, and snippets.

@leaysgur
Created July 11, 2014 17:10
Show Gist options
  • Save leaysgur/4abc2df47cb1a0677c75 to your computer and use it in GitHub Desktop.
Save leaysgur/4abc2df47cb1a0677c75 to your computer and use it in GitHub Desktop.
The Easiest way to typewrite text.
/**
* TypeWriter的な動きを実装するスニペット
* 気になる点としては、不完全な文字(<s とかタグの途中とか)をそのままHTMLとしてDOMに突っ込むので、
* うまく解釈してくれないやつがいたらバグりそう
*/
var str = "<p>This is my <span style='color:red;'>special string</span> with <br><br>an <img src='http://placehold.it/150x150'> image !</p>",
i = 0,
isTag,
dest = document.getElementById('hoge'),
text;
(function type() {
text = str.slice(0, ++i);
if (text === str) return;
dest.innerHTML = text;
var char = text.slice(-1);
if( char === '<' ) isTag = true;
if( char === '>' ) isTag = false;
if (isTag) return type();
setTimeout(type, 80);
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment