2

This is a basic question but most examples I find are a little bit too complex.

I am trying to create an array of photos, and then display only a selected one.

This is my array:

var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = 'images/pie1a.png';
imgArray[1] = new Image();
imgArray[1].src = 'images/pie1b.png';
imgArray[2] = new Image();
imgArray[2].src = 'images/pie2a.png';
imgArray[3] = new Image();
imgArray[3].src = 'images/pie2b.png';

This is my HTML:

<img src=imgArray[1] width="33" height="32">

I also tried this:

document.write('<img src="' + imgArray[1] + '" width="120" height="120"/>');    

The photo is never displayed. What am I doing wrong?

j08691
  • 204,283
  • 31
  • 260
  • 272

2 Answers2

2

Try this:

var imgArray = [
    'images/pie1a.png',
    'imgaes/pie1b.png',
    // ...
];
document.write('<img src="'+imgArray[1]+'" width="120" height="120" />');

Note that document.write is not a good idea, it should be avoided, but if it at least gets your code working it's a good start!

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • I agree. You're better off giving the original image an ID and use: document.getElementById("name").src = imgArray[1] – durbnpoisn Apr 11 '14 at 14:32
1

With this:

imgArray[3] = new Image();
imgArray[3].src = 'images/pie2b.png';

you need to write:

document.write('<img src="' + imgArray[3].src + '"/>'); 
// please note the '.src'
phylax
  • 2,034
  • 14
  • 13