Link to home
Create AccountLog in
Avatar of Sheils
SheilsFlag for Australia

asked on

How to loop through images with javascript

I am trying to loop through some images using this script

<html>
<head>

<script type="text/javascript" >

function PhotoDisplay

{

var images=['pic0.jpg','pic1.jpg','pic2.jpg','pic3.jpg','pic4.jpg']

for (i=0;i<images.lengh;i++)

{var img =new Image();
img.src=images[i]

}

}

window.onload = PhotoDisplay
</script>

</head>
<body>


<img src =img>

</body></html>

Open in new window


need some help to make the code work
Avatar of leakim971
leakim971
Flag of Guadeloupe image

You want to insert all the image in the page ? You're close, you just need to append the new created image to the body :


<html>
<head>
<script type="text/javascript" >
function PhotoDisplay
{
   var images=['pic0.jpg','pic1.jpg','pic2.jpg','pic3.jpg','pic4.jpg']
   for (i=0;i<images.lengh;i++)
   {
      var img = document.createElement("img");
      img.src = images[i]
      document.getElementsByTagName("body")[0].appendChild(img);
   }
}
window.onload = PhotoDisplay
</script>
</head>
<body></body></html>

Open in new window

Avatar of Sheils

ASKER

That gives me a blank page. I thought that something needs to go in the body
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of Sheils

ASKER

It works with the linked image that you posted but not with the image on my computer that I am trying to use. The names are corrert because thy display when I use <img src = "pic0.jpg">