1

I got into js few days ago. I started playing with new stuff functions and events but I got stuck here

var str = ["A", "b", "c", "d", "e"];

function Generate() {
  var text = document.getElementById("text");
  var countStr = 0;
  text.innerHTML = str[countStr];
  countStr += 1;

}
<div id="quote">
  <p id="text">I'm a paragraph</p>
</div>
<button id="butt" onclick="Generate()">Generate</button>

when I click the button the text changes to str[0] but when I click again it doesn't change; can you tell me why ?

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
youngtoken
  • 21
  • 2
  • 9

2 Answers2

7

This behaviour exists because everytime you click button, countStr variable will be 0. You need to declare it outside the function.

var str = ["A", "b", "c", "d", "e"];
var countStr = 0;
function Generate() {
  var text = document.getElementById("text");  
  text.innerHTML = str[countStr];
  countStr += 1;

}
<div id="quote">
  <p id="text">Im a paragraph</p>
</div>
<button id="butt" onclick="Generate()">Generate</button>

Another method is to use a closure function.

Read more about closures, here.

var str = ["A", "b", "c", "d", "e"];
var text = document.getElementById("text");
var generate=(function() {  
  var countStr = 0;
  return function(){
     text.innerHTML = str[countStr];
     return countStr+=1;
  }

})();
<div id="quote">
  <p id="text">I'm a paragraph</p>
</div>
<button id="butt" onclick="generate()">Generate</button>
Community
  • 1
  • 1
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
4

Because your countStr variable is local scoped. It means, when you call the function Generate(), it everytime creates a new countStr variable and set's it's value to 0 and for improvement put the document.getElementById("text") also outside the function.

Put it outside of the function.

var str = ["A", "b", "c", "d", "e"];
var countStr = 0;

var text = document.getElementById("text");

function Generate() {      
  text.innerHTML = str[countStr];
  countStr += 1;
}
<div id="quote">
  <p id="text">Im a paragraph</p>
</div>
<button id="butt" onclick="Generate()">Generate</button>
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
  • Probably someone voting before you finished your answer – mplungjan Jan 16 '17 at 14:40
  • sorry to bother you but i got another question :c is it possible to not use "onclick="generate()" in html and instead i use button.addEvenetListener("click",Generate(){}; ? does it work the same as the first one ? – youngtoken Jan 16 '17 at 14:55
  • `onclick="generate()` will work in every browser, but `addEvenetListener` will not work in Internet Explorer. For IE you need to use `attachEvent`. But in global, they are the same, but the best practice is to use code attachment as the second case. – Suren Srapyan Jan 16 '17 at 14:58