0

How to loop through an array with next and previous buttons?

// This is the code I have so far for two buttons. They're working as expected when I only click one button multiple times, but when I switch buttons, it doesn't pick up from the current array index. How can I make the buttons pick up where the current index of the array left off? I'm thinking another variable is needed but don't know how to get the array index in general. Thank you for any help! var colourLoop = [ 'Green', 'Orange', 'Blue', 'Yellow', 'Black' ]; var curNum = 0; //curNum means 'current number' function nextFunction(){ x = document.getElementById("paragraph"); x.innerHTML = (colourLoop[curNum]); if (curNum === 4) { curNum = 0; } else { curNum++; } } function prevFunction(){ x = document.getElementById("paragraph"); x.innerHTML = (colourLoop[curNum]); if (curNum === 0) { curNum = 4; } else { curNum--; } }

20th Jul 2020, 2:35 AM
DMo
2 Respostas
0
Update curNum before you change the innerHTML. The way it's currently written causes the buttons to be one change behind
20th Jul 2020, 5:20 AM
JME
0
This makes sense and it's now working! Thank you!
21st Jul 2020, 3:26 AM
DMo