Reputation: 91
I need to display a list of images from an array and also make it clickable to display some text on click. Looking for some simple solution only with javascript.
var images = ["img1", "img2", "img3"];
var allPics = images.length;
var i = 0;
for(;i<allPics; i++){
myImg.src = images[i];
}
Example here: https://jsfiddle.net/gmqLtd1u/1/
Now only one image is displayed.
Upvotes: 0
Views: 3092
Reputation: 1210
Now only one image is displayed.
Because you're using one <img>
and update its src
several times in loop. After last iteration, its src
is not updated anymore. That's why you see the last image.
Change your html, so that instead of <img>
you have <div>
as container/placeholder:
<!-- <img id="myImg"/> -->
<div id="myImg"></div>
And change your JS, to create <img>
and append it to <div>
:
for(;i<allPics; i++){
// myImg.src = images[i];
// TODO: adjust this to whatever you want
// in this example, use `<a>` that link to another page
// you can use javascript to show modal/alert too
var a = document.createElement('a');
a.href = 'example.html'; // TODO: adjust this
var img = document.createElement('img');
img.src = images[i];
a.appendChild(img);
document.getElementById('myImg').appendChild(a);
}
And maybe your CSS, to match with new output:
#myImg img {
...
}
Upvotes: 1