This page looks best with JavaScript enabled

Implementing Infinite Scroll

 ·  ☕ 4 min read


Unsplash has, at the time of writing, over 2 Million photos and an API that returns JSON. This was perfect in order to study how to implement an infinite scrolling mechanism using only Javascript.

Bottomless Pit Of Pictures

After signing up for an API key at the Unsplash developer portal it was time to roll a simple html page to host the Javascript script and a simple div with a class and id named ‘image-container’ in order to target for our infinite scroll container.

1
<div class="image-container" id="image-container"> </div>

Some simple CSS to style this can be added as a bonus.

1
2
3
4
5
6
7
8
.image-container { 
margin: 10px 30%; 
} 

.image-container img { 
width: 100%; 
margin-top: 5px; 
}

Here we’re just targeting the image container to have some margin on the top and to leave 30% on the left and right and additionally the image element to fill the width and have a little top margin from image to image in our infinite scroll.

Displaying data on the html page with Javascript

Having the html and css out of the way - we can now study the pieces that go into the infinite scroll mechanism in Javascript.

In order to have something to show we need to fetch a set of photos (say 30) such that we can fill our image container. Below is a getPhotos function that uses the Unsplash API to fetch 30 random photos using a fetch in a try-catch block and puts them into an array.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
let photosArray = []
const apiURL = `https://api.unsplash.com/photos/random/?client_id=${apiKey}&count=30`

// Get photos from Unsplash API 
async function getPhotos() { 
 try { 
   const response = await fetch(apiURL) 
   photosArray = await response.json() 
   displayPhotos() 
 } catch (error) {
     console.log("Seems to be some error")
   }
}

Having fetched the photos we can display the photos using the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// Create Elements for Links & Photos, Add to DOM 
function displayPhotos() { 
 // Run function for each object in photosArray 
 photosArray.forEach(photo => { 
 // Create <a> element to link to Unsplash 
   const item = document.createElement('a') 
   item.setAttribute('href', photo.links.html) 
   item.setAttribute('target', '_blank') 
 // Create an <img> element for photo 
   const img = document.createElement('img') 
   img.setAttribute('src', photo.urls.regular) 
   img.setAttribute('alt', photo.alt_description) 
   img.setAttribute('title', photo.alt_description) 
 // Put <img> inside <a>, then put both inside imageContainer element
   item.appendChild(img) 
   imageContainer.appendChild(item) 
 }) 
 console.log(photosArray) 
}

In displayPhotos we use a forEach to iterate through the photosArray and for each photo object create an anchor element and an image element and set the appropriate attribute from the Unsplash API JSON return call.

This should now display a list of the thirty photos fetched in a scrollable column.

Scrollable Column

Now we can start.

Defining a Trigger point

The idea of the infinite scroll is to define a trigger point, the number of pixels from the bottom of the scroll view, to start loading a new set of 30 photos.

The Trigger Point

That way, when you reach the trigger point, it is far enough away from the bottom that by the time you do get to the bottom you would have loaded the new set and they are already ready to display.

We’ll do this by defining a triggerPoint const.

1
const triggerPoint = 1000

Then adding an event listener that listens to the scroll event.
For each scroll it checks if the inner height + the scroll height is equal to or greater than the trigger point – then call the getPhotos() function again.

1
2
3
4
5
6
7
8
// Check to see if scrolling near bottom of page, load more photos 
window.addEventListener('scroll', () => { 
 if (window.innerHeight + window.scrollY >= 
       document.body.offsetHeight - triggerPoint) { 
   getPhotos() 
   console.log('Loading spot achieved') 
 } 
}) 

Keep scrolling

Now you should have a scrollable area that fills up with more photos as you reach your trigger point and provides the illusion of a bottomless pit of photos.

To see the full source to this project visit the project repo on github.

Share on

TinmanJS
WRITTEN BY
TinmanJS
Fullstack JS Developer