How to create a typewriter effect in JavaScript that will respect html tag rules?

Suppose I had text from a div tag, for example:

<div id="outPutContainer"> <div id="contentDiv" style="display:none;"> This is some cool content... </div> </div> 

Now, if I wanted to, I could create a JavaScript function that will print characters one at a time, and everything will work fine. An example is below.

 function printSentence(inner, outer, index, speed) { var input = document.getElementById(inner).innerHTML; var timer = setInterval(function(){ document.getElementById(outer).innerHTML+=input.charAt(index); index++; if(index == sentence.length -1){ printResume(inner, outer, index+1, speed); }else{ clearInterval(timer); } }, speed); } printSentence("contentDiv", "outPutContainer", 0, 100); 

Again, the above function works fine, however let me want to consider the html tags inside the element, how it will work. Example:

 <div id="contentDiv2"> This is some cool <strong>content</strong> <p>Paragraph of content</p> </div> 

Thus, the ideal effect would be

This is awesome content.

Paragraph of content

(The typewriter effect was inspired by Charlie) "I like giving credit where credit should be" (: Javascript print effect

I suggest that I can add jsFiddle to make it easier for people. http://jsfiddle.net/bJxe3/19/

+5
source share
1 answer

Instead of adding a character at a time, you can update the contents of a substring of a string to an index. If the character in the index is less than the sign (<), just go to the next character more (>).

Excerpt:

 function printSentence(id, sentence, speed) { var index = 0, timer = setInterval(function() { var char= sentence.charAt(index); if(char === '<') index= sentence.indexOf('>',index); document.getElementById(id).innerHTML= sentence.substr(0,index); if(++index === sentence.length){ clearInterval(timer); } }, speed); } //printSentence printSentence( 'contentDiv', 'This is some cool <strong>content</strong>.<p>Paragraph of content</p><ul><li>This<li>is<li>a<li>test</ul><table><tr><th>Header 1<th>Header 2<tr><td>Row 2, Col 1<td>Row 2, Col 2</table>', 50 ); 
 body, table {font: 12px verdana;} table {border-spacing: 0;} td,th {border: 1px solid gray;} th {background: #def;} 
 <div id="contentDiv"></div> 
+10
source

All Articles