Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a typewriter effect in JavaScript THAT will take into account html tag rules?

Tags:

javascript

Suppose I had some text from a div tag like this:

 <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 the characters one at a time and it will work just fine. Example 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 just fine, however let's say I wanted to take into account html tags within the element, how would that work. An example would be

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

So the ideal effect would be

This is some cool content

Paragraph of content

(The typewriter effect was inspired by Charlie) "I like to give credit where credit is due" (: Javascript typing effect

I suppose I can throw in a jsFiddle to make easier on folks. http://jsfiddle.net/bJxe3/19/

like image 648
dragonore Avatar asked Apr 05 '15 21:04

dragonore


1 Answers

Instead of adding a character at a time, you could update the content with a substring of the string up to the index. If the character at the index is a less-than sign (<), simply skip ahead to the next greater-than sign (>).

Snippet:

const printSentence = (id, sentence, speed = 50) => {
  let index = 0;
  let element = document.getElementById(id);
  
  let timer = setInterval(function() {
    const char = sentence[index];
    
    if (char === '<') {
      index = sentence.indexOf('>', index);  // skip to greater-than
    }
    
    element.innerHTML = sentence.slice(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>
like image 141
Rick Hitchcock Avatar answered Oct 26 '22 18:10

Rick Hitchcock