Question:
Good/Good Morning/Afternoon/Night, I would like some help in JavaScript, how do I execute data from an array always in the same order, example:
var teste = ["valor1", "valor2"];
document.getElementById("id").innerHTML =
How do I make when I click a button the text value is one, then when I click again it is two, and then restart. Thanks, sorry for the huge question 😉
Answer:
You have to create a variable that stores the information of which element of the array was shown. An index flag. And then every time you click on the element you increase that value variable.
An example would be like this:
var arr = ['Olá', 'hoje', 'esteve', 'um', 'lindo', 'dia!'];
var index = 0;
var btn = document.querySelector('button');
var div = document.querySelector('div');
btn.addEventListener('click', function() {
div.innerHTML = arr[index];
index++;
if (index == arr.length) index = 0;
});