0

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?

2
  • With this code, both functions can access invalid positions of the array pictures depending on the sequence of calls. For example, if MoveOneDown sets i = countthearray, then the function MoveOneUp is called, you will access position countthearray + 1 Commented Dec 6, 2014 at 17:46
  • What do you mean " only then it returns the array length value" - you are not accessing the array length in those functions. Commented Dec 6, 2014 at 17:50

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.