Author Photo
Christopher Unum I am a software Developer, I write web development tutorials, I also mentor aspiring web developers. s

how to add images dynamically on webpage using javascript






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.

Prerequisite

Basic knowledge of Html, CSS, and JavaScript are required to fully understand the concepts in this tutorial.

Html

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>

CSS

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{
  margin20px 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{
  floatright;
  bordernone;
  padding5px 12px;
  margin20px 0;
  background#004B92;
  colorwhite;
  cursorpointer;
}

@media only screen and (max-width:390px){
  #image-out{
    width:100%;
  }
}

JavaScript

Now to make the Add Image button work, we will be adding some JavaScript code.

//array of images
const 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 clicks
document.querySelector("#add-image").addEventListener("click", () => {
  addImage();
});

//aids in looping through the array
let x = 0;
const addImage = () => {
  //creates a div element
  let imageOut = document.createElement("div");
  //sets the id of the div
  imageOut.setAttribute("id","image-out");
  let imageIn = document.createElement("div");
  imageIn.setAttribute("id","image-in");
  //cereates an image element
  let img = document.createElement("img");
  //adds image to the image element
  img.src=images[x];
  imageIn.appendChild(img);
  imageOut.appendChild(imageIn);
  document.querySelector("#images-container").appendChild(imageOut);

  x++;

  //aids in looping through the array indefinitely
  if(x==10) x=0;
};

Conclusion

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.