JAVASCRIPT

Implement an Infinite Scroll Loader

Create an infinite scrolling effect to load more content automatically when users reach the bottom of a page or scrollable container.

document.addEventListener('DOMContentLoaded', () => {
  const contentContainer = document.getElementById('scrollableContent');
  let isLoading = false;
  let itemCount = 0;

  function loadMoreItems() {
    if (isLoading) return;
    isLoading = true;

    console.log('Loading more items...');
    // Simulate API call or data fetching
    setTimeout(() => {
      for (let i = 0; i < 10; i++) {
        itemCount++;
        const newItem = document.createElement('p');
        newItem.textContent = `Item ${itemCount} - Loaded dynamically`;
        contentContainer.appendChild(newItem);
      }
      isLoading = false;
      console.log('Items loaded.');
    }, 1000); // Simulate network delay
  }

  // Initial load
  loadMoreItems();

  contentContainer.addEventListener('scroll', () => {
    // Check if scrolled to the bottom (within a threshold)
    const scrollHeight = contentContainer.scrollHeight;
    const scrollTop = contentContainer.scrollTop;
    const clientHeight = contentContainer.clientHeight;
    const threshold = 100; // Load more items when 100px from bottom

    if (scrollTop + clientHeight >= scrollHeight - threshold) {
      loadMoreItems();
    }
  });
});
/*
HTML structure example:
<style>
  #scrollableContent {
    height: 300px;
    overflow-y: scroll;
    border: 1px solid #ccc;
    padding: 10px;
  }
</style>
<div id="scrollableContent">
  <p>Initial Item 1</p>
  <p>Initial Item 2</p>
</div>
*/
How it works: This snippet implements an infinite scroll mechanism. It monitors the 'scroll' event on a specified container. When the user scrolls close to the bottom (defined by a 'threshold'), a 'loadMoreItems' function is triggered. This function simulates fetching new data and appends new elements to the container, creating a seamless loading experience. A 'isLoading' flag prevents multiple simultaneous loads.

Need help integrating this into your project?

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

Hire DigitalCodeLabs