MarisP
MarisP

Reputation: 987

Making array elements change with JavaScript and buttons

Code:

var pictures = ["url(bildes/unity.png)", "url(bildes/xna.png)", "url(bildes/bge.png)"];
var countthearray = pictures.length;
var i = 0;
function MoveOneUp(){
    i++;
    document.getElementById("slaideris").style.backgroundImage=pictures[i];
    if (i == countthearray-1) {
        i =-1;
    }
}
function MoveOneDown(){
    --i;
    document.getElementById("slaideris").style.backgroundImage=pictures[i];
    if (i<0){
        i=countthearray;
    }
}

I'm trying to change the backgroundImage of a element via buttons, which have JS attached. If I use function MoveOneUp() everything works alright, but function MoveOneDown() seems to have some kind of problem that I don't understand.

Whenever I reach the last item of array, I have to click 2 times and only then it returns the array length value. Can someone explain me please where is the problem and how can I fix it?

Upvotes: 0

Views: 148

Answers (2)

T J
T J

Reputation: 43156

Try checking for boundaries before actually using the value to set the background:

var pictures = ["url(bildes/unity.png)", "url(bildes/xna.png)", "url(bildes/bge.png)"],
countthearray = pictures.length,
i = 0,
slider = document.getElementById("slaideris"); // cache the element

function MoveOneUp(){
  if (i == countthearray)
    i = 0;
  slider .style.backgroundImage=pictures[i];
  i++;
}
function MoveOneDown(){
  if (i<0)
    i=countthearray -1;
  slider .style.backgroundImage=pictures[i];
  --i;
}

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Remove the if blocks.

Then define this helper function:

function clamp(i, c) {
    return (i % c + c) % c;
}

You can then access pictures[clamp(i,c)] when needed.

Upvotes: 0

Related Questions