I'm trying to write a simple jquery "addon" that types text out for me, like a typewriter.
This is what I've come up with so far:
jQuery.fn.typer=function(speed){
typed = this;
theText = typed.text().split('');
typed.text("");
$.each(theText, function(index, value){
setTimeout(function(){
typed.append(value);
},speed*index);
});
return;
};
$("#p0").typer(50);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id='p0'>This text will appear at the speed: 50</p>
This works perfectly fine until I try to get it to type out two sentences at once.
jQuery.fn.typer=function(speed){
typed = this;
theText = typed.text().split('');
typed.text("");
$.each(theText, function(index, value){
setTimeout(function(){
typed.append(value);
},speed*index);
});
return;
};
$("#p0").typer(50);
$("#p1").typer(100);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id='p0'>This text will appear at the speed: 50</p><br />
<p id='p1'>This text will appear at the speed: 100</p>
The result I get is: TThihs itesxt wtilel xaptpe arw ait lthle spaeepd:p 5e0ar at the speed: 100
Any clue on how I can stop this from happening?
Thanks in advance.