Reputation: 29
I made a simple Image slider in JS for practice, but for some reason the variable Amount is equal to 3, which it should be, I tested by printing 3, but for my if statements I have to divide by 2 for the first (which makes it work ((function next() )), but for the second it does not work if I divide by 2 or do Amount alone (the back() function)
I do not know why it is doing this, please can someone explain? Thanks!
var Images = ["http://www.industus.com/test/wat1.png", "http://www.industus.com/test/wat2.png", "http://www.industus.com/test/wat3.png"];
var CurrentImage = -1;
var Amount = Images.length;
function next() {
if (CurrentImage <= Amount /2) {
CurrentImage = CurrentImage + 1;
document.getElementById("Picture").src = Images[CurrentImage];
}
}
function back() {
if (CurrentImage >= Amount /2) {
CurrentImage = CurrentImage - 1;
document.getElementById("Picture").src = Images[CurrentImage];
}
}
Upvotes: 0
Views: 171
Reputation: 817228
For going forward, you want to test whether the index is smaller than the largest valid index, with is Amount - 1
CurrentImage < (Amount-1)
For going backwards, you want to test whether the index is larger that the smallest valid index, which is 0
:
CurrentImage > 0
Upvotes: 1