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?

2
  • You have not pasted you HTML... Commented Apr 11, 2014 at 14:29
  • 1
    Shouldn't <img src=imgArray[1] width="33" height="32"> be <img src=imgArray[1].src width="33" height="32"> ? Commented Apr 11, 2014 at 14:31

2 Answers 2

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!

Sign up to request clarification or add additional context in comments.

1 Comment

I agree. You're better off giving the original image an ID and use: document.getElementById("name").src = imgArray[1]
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'

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.