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/
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With