0

I'm trying to loop through an array of images but can't seem to get past image 2.

The array should also loop back to 1 when the last image has passed...

    var WorkArray = new Array('work/01.png', 'work/02.png', 'work/03.png', 'work/04.png');

var nelements = WorkArray.length;

preload_image_object = new Image();
    var i = 0;
    for(i=0; i<=nelements; i++)  {
    preload_image_object.src = WorkArray[i];
    }

function cC() {
    var nelements = WorkArray.length;
    var i = 0;
    for(i=0; i<=nelements; i++)  {
    nelements = WorkArray[i];
    }
    document.getElementById("work").style.backgroundImage="url('"+WorkArray[i]+"')";
    }

3 Answers 3

1

You can save the current file and use modulo to run in cyclic manner.

It will look something like that:

var WorkArray = new Array('work/01.png', 'work/02.png', 'work/03.png', 'work/04.png');
var currentImage = 0

function nextImage(){
 currentImage = (currentImage + 1) % WorkArray.length;
 document.getElementById("work").style.backgroundImage="url('"+WorkArray[currentImage]+"')";
}
Sign up to request clarification or add additional context in comments.

Comments

1

You are overwriting nelements with the current element of the loop:

nelements = WorkArray[i];

Comments

0

The following should fix your loops:

var WorkArray = new Array('work/01.png', 'work/02.png', 'work/03.png', 'work/04.png');
var preload_image_object = new Image();

/* Lets get rid of `nelements`, as its just confusing. Get the length here. 
 * If, for performace reasons you want to use elements, the best way is to reverse
 * aka for(var i = WorkArray.length-1; i >= 0 ; i--)
 * Also, its simpler to declare the var in your for-loop itself instead of outside of it.
 */
for(var i = 0; i <= WorkArray.length; i++){
    preload_image_object.src = WorkArray[i];
}

Also, again for simplifications sake, your application of the background-image could be done inside your for loop as well, and can be made to look cleaner with some spaces and omitting the ' inside your url():

document.getElementById("work").style.backgroundImage = "url(" + WorkArray[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.