-1

I've asked this question already but I haven't been able to get many answers. I'll try and be more clear with this one!

I have an array which I am randomizing using math.random. I am displaying this array in the browser, each time the page refreshes it randomizes and outputs a different array item. Each array item contains a title and description which works, but I am also trying to add an image. I want this image to be displayed in the browser.

JavaScript:

var myArray = [
              {title: "my title", description: "my description", image: "file path"},
              ];

function getArray(ary){
  return ary[Math.floor(Math.random()*ary.length)];
}
var random = getArray(action);

and then in my HTML I have a <script> tag to display each portion of the item to the browser,

        document.write(random.title);
        document.write(random.description);
        document.write(random.image);

The problem is, the image doesn't show up it only displays the actual file path in text. How am I able to display the actual image?

roguerat
  • 219
  • 4
  • 16

3 Answers3

1

You are to place the html for the image, this way:

document.write('<img src="'+random.image+'" width="203" height="350" />');

Otherwise your random.image only shows the output of the array, which is text with "file path" written in it.

Mr.Web
  • 6,992
  • 8
  • 51
  • 86
  • Thank you so much! I've honestly spent hours on this and I don't know why I couldn't figure it out, but this made it all make sense. – roguerat Apr 04 '15 at 22:30
1

If you want to create the images dinamically, a possible way is the following:

var x = document.createElement("IMG");
x.setAttribute("src", "file.jpg");
document.body.appendChild(x);
Roger
  • 1,053
  • 1
  • 8
  • 14
0

Make it valid HTML. Like <img src="path">

And this is some random text because the answer was too short.

W van Rij
  • 536
  • 2
  • 16