Reputation: 671
Trying to get an element to change every x number of seconds. When I click the button it should change the innerHTML, looping through an array. The code below changes the text but displays the last result in the array.
<h1 id="header">Agent</h1>
<button id="change-header" onclick="loopHeader()">Click Me</button>
<script>
function loopHeader() {
var loopHeader = setInterval(changeText, 1000);
}
function changeText() {
var headers = ["Agent", "Expert", "Homes", "Service", "Results"];
var text = "";
var i = 0;
var x = document.getElementById("header");
for (i = 0; i < headers.length; i++) {
text = headers[i];
x.innerHTML = text;
}
}
</script>
Upvotes: 0
Views: 1275
Reputation: 31692
That's because every time you changeText
is called it start changing the innerHTML
of the button by the text from the array all from index 0 to the end (It's happening you just can't see it because it's happening fast). What you need is to define i
outside the function and every time the function is called increment i
and show its corresponding value from the array without a loop. Like this:
<button id="change-header" onclick="loopHeader()">Click Me</button>
<script>
function loopHeader() {
// if you want to start the animation just after the button is clicked, then uncomment the next line
// changeText();
var loopHeader = setInterval(changeText, 1000);
}
var i = 0; // i declared outside with the initiale value of 0
var headers = ["Agent", "Expert", "Homes", "Service", "Results"]; // this also should be outside (what's the point of redefining it every time the function is called)
function changeText() {
var x = document.getElementById("change-header"); // the id is change-header
// increment i and check if its beyond the boundaries of the loop, or just use modulo operator t prevent it from going beyond
i = (i + 1) % headers.length;
x.textContent = headers[i]; // textContent is better than innerHTML
}
</script>
Upvotes: 0
Reputation: 708
Move the count outside of the function, and then keep looping round and resetting to 0 when at end.
function loopHeader() {
var loopHeader = setInterval(changeText, 1000);
}
var headers = ["Agent", "Expert", "Homes", "Service", "Results"];
var loopItem = 0;
function changeText() {
loopItem++;
if (loopItem == headers.length) {
loopItem = 0;
}
document.getElementById("header").innerHTML = headers[loopItem];
}
</script>
<div id="header">
</div>
<button id="change-header" onclick="loopHeader()">Click Me</button>
Upvotes: 1