How To Display Images From A Javascript Array/object? Starting With The First Image Then Onclick To The Next
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 an
Solution 1:
See I did it like bellow
<script>var images = ['img/background.png','img/background1.png','img/background2.png','img/background3.png'];
var index = 0;
functionbuildImage() {
var img = document.createElement('img')
img.src = images[index];
document.getElementById('content').appendChild(img);
}
functionchangeImage(){
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><bodyonload="buildImage();"><divclass="contents"id="content"></div><buttononclick="changeImage()">NextImage</button></body>
I was not sure div
has an onload
event or not so I called onload
of body.
Solution 2:
// the containervar container = document.getElementById('content');
for (var i = 0; i < images.length; i++) {
// create the image elementvar imageElement = document.createElement('img');
imageElement.setAttribute('src', images[i]);
// append the element to the container
container.appendChild(imageElement);
}
For more information on how to perform DOM manipulation/creation, read up on MDN and other resources. Those will help a lot in your development.
Solution 3:
<body><imgid="thepic"/><inputtype="button"id="thebutt"value="see next"/><script>
(function (){
var images = ['img/background.png','img/background1.png','img/background2.png','img/background3.png'];
var imgcnt = 1;
functionchangeIt() {
if(imgcnt<images.length){
document.getElementById("thepic").src=images[imgcnt++];
} else{
console.log("done")
}
}
document.getElementById("thepic").src=images[0];
document.getElementById("thebutt").onclick=changeIt;
})();
</script></body>
Post a Comment for "How To Display Images From A Javascript Array/object? Starting With The First Image Then Onclick To The Next"