Skip to content
Advertisement

JavaScript load Images in an Array and Show in Image Source

I created an array of images

function initialize(){
//add our 10 images to our array
imgArray[imageNum++] = new imageItem(imageDir + "img1.jpg");
imgArray[imageNum++] = new imageItem(imageDir + "img2.jpg");
imgArray[imageNum++] = new imageItem(imageDir + "img3.jpg");

}
var totalImgs = imgArray.length;

I then create a function that is linked with a in my html file:

<button id="startButton" onclick="startImage()">Start</button>

function startImage(){

    document.getElementById("pic").setAttribute("src", imgArray[0].src);
}   

My image tag : <img id="pic" src="" height="300" width="500" border="0" alt="image"> This fails to update my img object, i used firebug to look at the DOM and my array is being populated properly but the img src is not be set?

Advertisement

Answer

Your example is incomplete. You need to show what the imageItem constructor does (and it’s convention to use a capital letter for the first character in a constructor), so:

function ImageItem(src) {
  this.image = new Image();
  this.src = src.
}

should do the job here. You also seem to want imgArray as a global, so declare it as one:

var imgArray;

function initialize(){
    //add our 10 images to our array 
    imgArray[imageNum++] = new imageItem(imageDir + "armory.jpg");

Assigning an array literal is a bit easier:

    imgArray = [ new ImageItem(imageDir + "armory.jpg"),
                 new ImageItem(imageDir + "eddy.jpg"),
                 ...
                 new ImageItem(imageDir + "...")
    ];
}

var totalImgs = imgArray.length;

Though I can’t see why you don’t just assign the array literal directly and not bother with the wrapper function. The startImage function can be a bit tidier:

function startImage(){
    document.getElementById("pic").src = imgArray[0].src;
}

Accessing element properties directly is more reliable across browsers and less to type than using setAttribute (which has quirks in some browsers).

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement