To customize the text animation, you can set the data-text
attribute with an HTML string and replace .text()
with .html()
in the typeIt()
function call.
var $typer = $('.typer'),
txt = $typer.data("text"),
tot = txt.length,
ch = 0;
(function typeIt() {
if(ch > tot) return;
$typer.html( txt.substring(0, ch++) );
setTimeout(typeIt, ~~(Math.random()*(200-60+1)+60));
}());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="typer" data-text='Hi. My <span style="text-decoration: underline;">name</span> is <span style="color: #ff0000;">Amir</span>. <strong>Nice too see you</strong> guys!
'></span>
Another way to achieve this effect is by creating a <template>
element, accessing the child nodes of the template content using .content.childNodes
, converting them into an array with Array.prototype.slice.call()
, and then iterating through each character of the data-text
HTML string using .reduce()
method along with .split("")
.
In the .reduce()
callback, utilize promises to handle asynchronous tasks such as waiting for a specified timeout before moving to the next step. Check if the node is a text node, if so, update the HTML of $typer
; otherwise, store the text content, empty the current node, append it to $typer
, and gradually display each character.
var $typer = $('.typer')
, txt = $("<template>", {
html: $typer.data("text")
})[0].content.childNodes;
Array.prototype.slice.call(txt).reduce(function(p, node) {
return p.then(function() {
var currentText = node.textContent.split("");
if (node.nodeType !== 3) {
var curr = node;
$typer.append($(node).empty());
}
return currentText.reduce(function(promise, text) {
return promise.then(function() {
return new Promise(function(resolve) {
setTimeout(function() {
$(curr || $typer).html(function(_, html) {
return html + text;
});
resolve()
}, ~~(Math.random() * (200 - 60 + 1) + 60))
})
})
}, Promise.resolve())
})
}, Promise.resolve());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<span class="typer" data-text='Hi. My <span style="text-decoration: underline;">name</span> is <span style="color: #ff0000;">Amir</span>. <strong>Nice too see you</strong> guys!
'></span>