I'm trying to cycle iterate through an array by using a 'previous' and 'next' button, respectively moving through the array.
It works fine until you change 'direction' and try say, for example 'next' then 'previous'
The array displays the same element it was already on instead of showing the previous element of the array.
For example, I am on 4, hit the 'previous' button and it remains on 4. You have to press the 'previous' button again to make it go back down to 3.
What am I missing here...?
var numbers = ["I am index number 0", "I am index number 1", "I am index number 2",
"I am index number 3", "I am index number 4", "I am index number 5"];
var i=0;
var text = "";
document.getElementById("back").addEventListener("click", function previous() {
if (i-1 >= 0) {
var text = numbers[--i];
}
document.getElementById("filler").innerHTML = text;
});
document.getElementById("forward").addEventListener("click", function next(){
if (i < numbers.length) {
var text = numbers[i++];
}
document.getElementById("filler").innerHTML = text;
});
<p id="filler"></p>
<button id="back">PREVIOUS</button>
<button id="forward">NEXT</button>
I modified your code below to make it work:
Only change I made is in
var text = numbers[i--];
I changed the position of the operator from left to right."If the operator appears before the variable, the value is modified before the expression is evaluated. If the operator appears after the variable, the value is modified after the expression is evaluated."
quoting from: https://docs.microsoft.com/en-us/scripting/javascript/reference/increment-and-decrement-operators-javascriptFirst of all you should look at the comment made by Crayon Violent
You should not redefine the text inside the ifs
This solution below works:
Actually what your looking is pre-increment and not post-increment.
++i
increments the value then returns the value, in the other handi++
returns the current value and then increments the value.Also another one advice, you don't need to create all the time the var
text
, once you create and define it empty, you better only dotext = numbers[--i]
withoutvar
.Another thing I noticed is that in your second conditional (if) you should do
if (i < numbers.length - 1)
because.length
method starts counting in 1.I made a jsfidddle for you :) https://jsfiddle.net/t2cjf5m8/16/