Loading images dynamically on the web can be very useful, especially when you are retrieving the images from a server or an API. In this tutorial, we will learn how to render images on the web from a list of images saved in an array. The interface above is fully function, feel free to try it out.
Basic knowledge of Html, CSS, and JavaScript are required to fully understand the concepts in this tutorial.
To begin, we need to write Html code upon which we will render our images.
<div id="board"><div id="images-container"><div id="image-out"><div id="image-in"><img src="images/image10.jpg" /></div></div></div><button id="add-image">Add Image</button></div>
Now we style the Html, giving it a better look and feel. We added a media query that changes the width of the images when the width of the screen approaches 390px.
#board{margin: 20px auto;max-width:600px;}#image-out{display:inline-block;width:49%;margin:2px 0;}#image-in{width:98%;margin:0 auto;}#image-in img{width:100%;}#add-image{float: right;border: none;padding: 5px 12px;margin: 20px 0;background: #004B92;color: white;cursor: pointer;}@media only screen and (max-width:390px){#image-out{width:100%;}}
Now to make the Add Image button work, we will be adding some JavaScript code.
//array of imagesconst images = ['images/image1.jpg','images/image2.jpg','images/image3.jpg','images/image4.jpg','images/image5.jpg','images/image6.jpg','images/image7.jpg','images/image8.jpg','images/image9.jpg','images/image10.jpg'];//listens for clicksdocument.querySelector("#add-image").addEventListener("click", () => {addImage();});//aids in looping through the arraylet x = 0;const addImage = () => {//creates a div elementlet imageOut = document.createElement("div");//sets the id of the divimageOut.setAttribute("id","image-out");let imageIn = document.createElement("div");imageIn.setAttribute("id","image-in");//cereates an image elementlet img = document.createElement("img");//adds image to the image elementimg.src=images[x];imageIn.appendChild(img);imageOut.appendChild(imageIn);document.querySelector("#images-container").appendChild(imageOut);x++;//aids in looping through the array indefinitelyif(x==10) x=0;};
We've come to the end of this tutorial, hope you were able to learn something new. you can leave a comment in the comments area if you need help.