Infinite Scroll in Vanilla Java Script

·

4 min read

Infinite scrolling is a feature found in many websites and apps designed to engage users seamlessly by continuously loading new data as they approach the bottom of a page, This dynamic functionality is prominently featured on platforms like Instagram and YouTube, where content effortlessly streams in as users scroll, ensuring that an uninterrupted flow of engaging content keeps them engaged.

Infinite scrolling isn't just a trend; it's a strategy that can transform casual visitors into dedicated followers. So, consider integrating this feature into your website or app to enhance the user experience, boost engagement, and gain a following that keeps growing. Your journey to attracting and retaining followers begins with a scroll – an infinite scroll.

How can we implement it?

To implement infinite scrolling effectively, it's crucial to have a solid understanding of some fundamental concepts related to the document's scrolling behavior in a web browser. These include the scroll height, client height, and scroll top properties of the documentElement. Let's dive into these essential details to shed light on how they form the foundation of infinite scrolling.

  1. Scroll Height: This property represents the entire height of the content within the scrollable element. In the context of a web page, it reflects the combined height of all the content on the page, including both the visible and hidden parts. Knowing the scroll height is vital for determining how much content is available beyond what's currently visible.

  2. Client Height: The client height of an element represents the height of the visible portion of that element within the browser's viewport. In other words, it tells us how much content can be seen without scrolling. Understanding the client height helps us gauge how much space is available for displaying content without overloading the viewport.

  3. Scroll Top: The scroll top property specifies the vertical scroll position of the scrollable element. It indicates how far down the user has scrolled from the top of the content. Monitoring the scroll top value allows us to track the user's position within the document, helping us decide when to load more content as they approach the bottom.

JavaScript Implementation

Now, let's dive into the JavaScript code that enables infinite scroll. We'll break down the key components step by step.

  1. Variables and Initial Fetch

     const container = document.querySelector(".container");
     let page = 1;
     let postId = 1;
     const postPerPage = 4;
    

    In this section, we define variables to keep track of the current page, the number of posts per page, and a variable to assign unique IDs to each post.

  2. Fetching Data

     const getPosts = async () => {
         try {
             const response = await fetch(`https://jsonplaceholder.typicode.com/posts?_page=${page}&_limit=${postPerPage}`);
             const data = await response.json();
    
             data.map((postItem) => {
                 const postHTML = `<div class="posts">
                                   <p class="post-id">${post++}</p>
                                   <h2 class="title">${postItem.title}</h2>
                                   <p class="post-info">${postItem.body}</p>
                                   </div>`;
                 container.innerHTML += postHTML;
             });
         } catch (error) {
             console.log("Error:", error);
         }
     };
    

    Here, we define an asynchronous function getPosts to fetch data from a remote server using the fetch API. The page and postPerPage variables are used as query parameters to control pagination. We are passing the dynamic data into the HTML code after fetching the data.

  3. Showing Data on Scroll

     const showData = () => {
         const { scrollTop, clientHeight, scrollHeight } = document.documentElement;
         //limit is 80 because I want to load data if user scrolled 80% of the page, 
         //you can set any limit here for loading the data on that particular point. 
         let limit = 80;
         let threshold = (scrollHeight - clientHeight) * (limit / 100);
    
         if (scrollTop > threshold) {
             page++;
             getPosts();
         }
     };
    
     window.addEventListener('scroll', () => {
         showData();
     });
    

    In this section, we create a function showData that calculates the scroll position and compares it to a threshold value. When the user scrolls beyond the threshold, we increment the page variable and call getPosts to fetch and append more data.

Conclusion

Infinite scroll is a powerful technique that can enhance user engagement by providing a smooth browsing experience. By implementing it you have full control over the behavior and appearance of your infinite scroll feature.

Feel free to adapt this code to your specific needs and integrate it into your web projects. With some customization, you can create a dynamic and user-friendly content-loading experience that keeps your visitors engaged.

That concludes our guide on implementing infinite scroll in vanilla JavaScript. Happy coding!