Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
98
rated 0 times [  99] [ 1]  / answers: 1 / hits: 22207  / 10 Years ago, wed, august 6, 2014, 12:00:00

Attempting to load images from my JavaScript array and display the first one the array. I then need to add a function that will allow the next image in the array to be displayed and so on till the end of the array.



<script>
var images = [ '/images/1.png', '/images/2.png' ];

function buildImages() {
for (var i = 0; i < images.length; i++) {
document.createElement(images[i]);
}
}
</script>

</head>
<body>
<div onload=buildImages(); class=contents id=content></div>
</body>


Within the images array are paths to the images. They look like server/images/05-08-2014-1407249924.png


More From » html

 Answers
11

See I did it like bellow



<script>
var images = ['img/background.png','img/background1.png','img/background2.png','img/background3.png'];
var index = 0;

function buildImage() {
var img = document.createElement('img')
img.src = images[index];
document.getElementById('content').appendChild(img);
}

function changeImage(){
var img = document.getElementById('content').getElementsByTagName('img')[0]
index++;
index = index % images.length; // This is for if this is the last image then goto first image
img.src = images[index];
}
</script>

<body onload=buildImage();>
<div class=contents id=content></div>
<button onclick=changeImage()>NextImage</button>
</body>


I was not sure div has an onload event or not so I called onload of body.



DEMO


[#69895] Monday, August 4, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ellisw

Total Points: 625
Total Questions: 92
Total Answers: 88

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
ellisw questions
Mon, Aug 23, 21, 00:00, 3 Years ago
Fri, Nov 20, 20, 00:00, 4 Years ago
Sat, Jun 20, 20, 00:00, 4 Years ago
Tue, Apr 21, 20, 00:00, 4 Years ago
;