JAVASCRIPT

Implement Infinite Scrolling for Paginated API Data

Create a seamless infinite scrolling experience on your web page by dynamically fetching and appending paginated data from an API as the user scrolls, optimizing data loading.

// HTML structure for example:
// <div id="container"></div>
// <div id="loader" style="display:none;">Loading...</div>

const container = document.getElementById('container');
const loader = document.getElementById('loader');
let currentPage = 1;
let isLoading = false;
let hasMore = true;

async function fetchItems(page) {
  isLoading = true;
  loader.style.display = 'block';
  try {
    // Replace with your actual API endpoint and pagination parameters
    const response = await fetch(`https://api.example.com/items?page=${page}&limit=10`);
    if (!response.ok) {
      throw new Error(`API Error: ${response.status} ${response.statusText}`);
    }
    const data = await response.json();
    // Assuming API returns an array of items and a way to know if there's more
    const items = data.items || []; // Adjust based on your API response structure
    hasMore = data.hasMore || items.length > 0; // Adjust 'hasMore' logic

    items.forEach(item => {
      const div = document.createElement('div');
      div.className = 'item-card';
      div.textContent = `Item ID: ${item.id}, Name: ${item.name}`; // Adjust to display item data
      container.appendChild(div);
    });

    currentPage++;
  } catch (error) {
    console.error('Error fetching items:', error);
    hasMore = false; // Stop trying if there's an error
  } finally {
    isLoading = false;
    loader.style.display = 'none';
  }
}

function handleScroll() {
  if (isLoading || !hasMore) return;

  const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
  if (scrollTop + clientHeight >= scrollHeight - 50) { // Trigger when 50px from bottom
    fetchItems(currentPage);
  }
}

// Initial load
fetchItems(currentPage);

// Attach scroll event listener
window.addEventListener('scroll', handleScroll);
How it works: This JavaScript snippet implements an infinite scrolling mechanism for fetching paginated data from an API. It listens for scroll events and, when the user approaches the bottom of the page, it triggers `fetchItems` to load the next page of data. State variables (`isLoading`, `hasMore`, `currentPage`) manage the fetching process, preventing multiple simultaneous requests and stopping requests when no more data is available. This pattern provides a smooth user experience for browsing large datasets without manual pagination clicks.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs