0

I have picture links that are stored in a array, and I change the background of a div using those picture links when a button is clicked.

So far everything is ok, but I don't understand how can I make the function return the first value of array ([0]) when the i value is greater than the array.length value.

Here's what I got:

function palabifunkcija(){
    document.getElementById('PictureContent').value= ++i;
    document.getElementById('PictureContent').style.background= bildes[i];
    if (i>bildes.length){
        return i=0;
    } 
}

Clicking makes the pictures change, but when the if statement executes, i have to click twice on the button and it displays 2nd picture (bildes[1]) not bildes[0].

Can anyone explain why it's so and how can I fix it, so it works properly?

Sorry for the bad english.

2 Answers 2

1

You can find the remainder of i divided by the array length.

var i = 0, 
    length = bildes.length;
function palabifunkcija(){
    i++;
    i %= length;
    document.getElementById('PictureContent').value = i;
    document.getElementById('PictureContent').style.background = bildes[i];
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, this works perfectly. Now I just have understand how it works.
It always 'normalizes' current index by total length preventing it to be larger than length. Suppose length is 3; 0%3 == 0, 1%3 == 1, 2%3 == 2, 3%3 == 0 etc
I still don't understand how it works. From what I understand- it devides the 2 numbers and shows what's left. I guess that's not the case and now i'm confused.
what would be the case if i'd like the same process to go backwards? I mean if i would like the array values to go like this- 0;4;3;2;1;0;4.... Will I need to use if statements or..? Can you give me a hint?
I think i--; i = i < 0 ? (length - 1) : i; will do the trick. Of course var i = length - 1
1

Try this

function palabifunkcija(){
    i = (i+1) % bildes.length;
    document.getElementById('PictureContent').value= i;
    document.getElementById('PictureContent').style.background= bildes[i];    
}

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.