# How to Implement Infinite Scroll with Vanilla JavaScript

By [TC Wang](https://paragraph.com/@tc-wang) · 2022-05-12

---

![https://tingchun0113.github.io/infinite-scroll-unsplash-api/](https://storage.googleapis.com/papyrus_images/08ef3e0681dc7db66c3b9e4fe60ed51e73363093619b92168eaad10ac65ecbe3.gif)

https://tingchun0113.github.io/infinite-scroll-unsplash-api/

**Infinite scroll** is often used on social media sites such as Twitter or Pinterest. The feature allows users to load some pictures/contents on a website and then load more once reaching the end of the webpage.

I used [Unsplash API](https://unsplash.com/documentation) to get random pictures. This article will focus on how to use JavaScript to make use of some properties to achieve infinite scroll. You can find other project files (HTML or CSS files) in this [repo](https://github.com/tingchun0113/infinite-scroll-unsplash-api).

Four Properties to Achieve Infinite Scroll
------------------------------------------

A) **window.scrollY**: How far the document has been scrolled from the top

B) **window.innerHeight**: The visible part of the window

C) **document.body.offsetHeight**: The height of the entire document

D) 1000px (or any value): The distance from bottom of document

The diagram below better illustrates these properties:

![JavaScript Web Projects: 20 Projects to Build Your Portfolio](https://storage.googleapis.com/papyrus_images/b7243cc8eee216d3932403777d0c048819fdb42ac601ec4d1792b9674268c310.png)

JavaScript Web Projects: 20 Projects to Build Your Portfolio

Looking at the above, we can listen to the scroll event:

If A (scrollY) + B (innerHeight) >= C (document height) - D (1000px)  
\-> load more photos

    // Check to see if scrolling near bottom of page; load more photos
    window.addEventListener('scroll', () => {
      if (
        window.scrollY + window.innerHeight >= document.body.offsetHeight - 1000
      ) {
        getPhotos();
      }
    });
    

[https://gist.github.com/tingchun0113/6b63e548936ac161f6109f787d90f719#file-script-js](https://gist.github.com/tingchun0113/6b63e548936ac161f6109f787d90f719#file-script-js)

Final Thoughts
--------------

There’re other tools ([Intersection Observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API)) to implement infinite scroll. If you find this article useful or have any questions, connect me on [**LinkedIn**](https://www.linkedin.com/in/tingchunw/) or follow me on [**Medium**](https://tingchun0113.medium.com/) for more articles.

---

*Originally published on [TC Wang](https://paragraph.com/@tc-wang/how-to-implement-infinite-scroll-with-vanilla-javascript)*
