xoxo_tw
xoxo_tw

Reputation: 269

JavaScript Image from random Object?

I have a Button when pressed should: Randomly present Text Information about 3 Objects.

Now I have added String: 'Photo' to each Object, that holds the photo fileName of it.

Now I have problem with assigning the filename in my random Function correctly.

The target for the Photo is: 'pic'

Im not sure if this is valid:

chatObj.photo[randomImageIndex]

relative from where my script is located the path to the images is:

"../images"

Im not sure if this is correct:

"<img alt=\"\" src=\"/../images" + chatObj.photo[randomImageIndex] + "\" />"


var Dog = Object.spawn(Creature, {
  type: "DOG",
  legs: 4,
  age: 6,
  name: "Charlie",
  funx: "Run in a circle",
  photo: "dog.jpg",
});



function qRandom(){
    var chatObj = new Array();
    chatObj[0] = obj1;
    chatObj[1] = obj2;
    chatObj[2] = obj3;
    var randomIndex = Math.round(Math.random() * 2);

  document.getElementById('pic').innerHTML = "<img alt=\"\" src=\"/../images" + chatObj.photo[randomImageIndex] + "\" />"
}

Upvotes: 0

Views: 65

Answers (1)

Andrzej Doyle
Andrzej Doyle

Reputation: 103837

If each object has a Photo field, then you need to look up the random object first and then get its string field, like so:

chatObj[randomImageIndex].photo

rather than the other way round as you do above.

(Also, I would change the name of the array so that it sounds plural, something like chatObjs or chatObjArray etc. At the moment chatObj sounds to me like a single chat object, so it feels strange to look up a particular index.)

Upvotes: 1

Related Questions