Search code examples
javascripthtmlgalleryphoto

How to use your own photos for infinite scroll effect


I have an infinite scroll project, and I don't really want to use API like picsum and unsplash to generate random photos. I want to use my own photos either from somewhere on the internet or locally saved. I follow a tutorial to make my photo gallery infinite scroll, but I don't understand how to change picsum url to something else. Preferably locally saved photos. I could name them with numbers from 1 to 20 for example, but how do I write the "fetch" part?

const getImages = async function() {
  const getImageRes = await fetch(
    `https://picsum.photos/v2/list?page=${page}&limit=8`
  );
  const data = await getImageRes.json();
  const loading = document.querySelector(".loading");

  for (let i = 0; i < 8; i++) {
    let ele = document.createElement("img");
    ele.setAttribute("src", data[i].download_url);
    ele.setAttribute("height", "384");
    ele.setAttribute("width", "512");
    document.getElementById("container").appendChild(ele);
  }
  page++;
  loading.classList.remove("show");
};


Solution

  • const imageSources = [ // Put your image sources in this list
      './images/1.jpg',
      './images/2.jpg',
      './images/3.jpg',
      './images/4.jpg',
      './images/5.jpg'
    ]
    
    for (let i = 0; i < 5; i++) { // Change this 5 to however many images you have (or use for ... in) 
        let ele = document.createElement("img");
        ele.setAttribute("src", imageSources[i]);
        ele.setAttribute("height", "384");
        ele.setAttribute("width", "512");
        document.getElementById("container").appendChild(ele);
      }
      page++;
      loading.classList.remove("show");
    };