Skip to content Skip to sidebar Skip to footer

How To Create A Typewriter Effect In JavaScript THAT Will Take Into Account Html Tag Rules?

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

Solution 1:

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>

Post a Comment for "How To Create A Typewriter Effect In JavaScript THAT Will Take Into Account Html Tag Rules?"