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.
|
|
Some simple CSS to style this can be added as a bonus.
|
|
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.
|
|
Having fetched the photos we can display the photos using the following code:
|
|
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.
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.
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.
|
|
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.
|
|
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.