0

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.

User K
  • 380
  • 3
  • 16

1 Answers1

3

Declaring a variable without using the var keyword puts the variable in the global scope. See this question for more details.
As such, both instances share the variables and result in the gibberish you see above.

jQuery.fn.typer=function(speed){
  var typed = this;
  var 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>
Community
  • 1
  • 1
Etheryte
  • 24,589
  • 11
  • 71
  • 116