I have a button that displays one array string with each push, in order from top to bottom. I am trying to figure out a way to display the strings from bottom to top (reverse order). I've added two snippets below to show what I've got so far. The top snippet is the functioning button that displays the numbers in forward order, and the bottom snippet is what I've tried so far to reverse the function, to no avail. What needs to be done to tell the function to display 888
first, then 777
, 666
, 555
, and so on?
var textCount = 0;
var oddtext = [
'111',
'222',
'333',
'444',
'555',
]
function newThing() {
document.getElementById('thingDisplay').innerHTML = oddtext[textCount];
textCount++;
if (textCount >= oddtext.length) textCount = 0;
}
<div align="center" id='thingDisplay'></div>
<button class="box" id="button01" onclick="newThing()">New Thing</button>
var textCount = 0;
var oddtext = [
'111',
'222',
'333',
'444',
'555',
]
function newThing() {
oddtext.reverse();
document.getElementById('thingDisplay').innerHTML = oddtext[textCount];
textCount++;
if (textCount >= oddtext.length) textCount = 0;
}
<div align="center" id='thingDisplay'></div>
<button class="box" id="button01" onclick="newThing()">New Thing</button>
For your code to work you should remove reverse()
and start from the length of the array -1 all the way to 0
var oddtext = [
'111',
'222',
'333',
'444',
'555',
'666',
'777',
'888'
]
textCount=oddtext.length-1
function newThing() {
document.getElementById('thingDisplay').innerHTML = oddtext[textCount];
textCount--;
if (textCount<0) textCount=oddtext.length-1
}
<div align="center" id='thingDisplay'></div>
<button class="box" id="button01" onclick="newThing()">New Thing</button>
Alternatively if you want to use reverse, you have to start the count from index 0
to array.length-1
var oddtext = [
'111',
'222',
'333',
'444',
'555',
'666',
'777',
'888'
]
oddtext.reverse()
var textCount = 0;
function newThing() {
document.getElementById('thingDisplay').innerHTML = oddtext[textCount];
textCount++;
if (textCount>oddtext.length-1) textCount=0
}
<div align="center" id='thingDisplay'></div>
<button class="box" id="button01" onclick="newThing()">New Thing</button>