Reputation: 152
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 ?
Upvotes: 1
Views: 1141
Reputation: 48417
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>
Upvotes: 6
Reputation: 68675
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>
Upvotes: 4