Master Infinite Scroll in JavaScript with Just a Few Lines of Code bilal shafqat

Master Infinite Scroll in JavaScript with Just a Few Lines of Code

Learn how to implement master infinite scroll in javascript using just a few lines of code. Ideal for developers who want to boost UX without heavy libraries.

Why Use Infinite Scroll?

Infinite scroll loads more content as the user reaches the bottom of the page, keeping the experience fluid. It’s great for blogs, social feeds, and product listings—where users love continuous browsing.

1. Detect When the User Reaches the Bottom

Detect When the User Reaches the Bottom bilal shafqat

Goal: Trigger an action when the user scrolls to the end of the page.

window.addEventListener('scroll', () => {
  if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
    loadMoreContent();
  }
});

Explanation:
This checks if the user’s scroll position is at the bottom and calls loadMoreContent().

2. Mock Fetching More Data with Timeout

Mock Fetching More Data with Timeout bilal shafqat

Goal: Simulate an API call or delay to mimic real-world data fetching.

function fetchData() {
  return new Promise((resolve) => {
    setTimeout(() => {
      const items = Array.from({ length: 10 }, (_, i) => `Item ${i + 1}`);
      resolve(items);
    }, 1000);
  });
}

Explanation:
This mimics a network call and returns an array of dummy items after a delay.

3. Show a Loader While Fetching

Show a Loader While Fetching bilal shafqat

Goal: Indicate that content is loading to enhance user experience.

<div id="loader" style="display:none;">Loading...</div>
function showLoader(show) {
  document.getElementById('loader').style.display = show ? 'block' : 'none';
}

Explanation:
A simple div acts as a loading indicator that shows/hides based on fetch state.

4. Render and Append New Items to the DOM

Render and Append New Items to the DOM bilal shafqat

Goal: Add fetched items to the page without reloading.

function appendItems(items) {
  const container = document.getElementById('content');
  items.forEach(item => {
    const div = document.createElement('div');
    div.textContent = item;
    container.appendChild(div);
  });
}

Explanation:
This dynamically adds each new item as a div into the content container.

5. Use Debounce to Improve Scroll Performance

Use Debounce to Improve Scroll Performance bilal shafqat

Goal: Prevent multiple unnecessary function calls during rapid scrolling.

function debounce(func, delay) {
  let timeout;
  return function (...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, args), delay);
  };
}
window.addEventListener('scroll', debounce(() => {
  if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
    loadMoreContent();
  }
}, 200));

Explanation:
Debouncing avoids performance issues by delaying execution until scrolling stops for a set time.

Full Working Example

<body>
  <div id="content"></div>
  <div id="loader">Loading...</div>

  <script>
    let loading = false;

    async function loadMoreContent() {
      if (loading) return;
      loading = true;
      showLoader(true);

      const items = await fetchData();
      appendItems(items);

      showLoader(false);
      loading = false;
    }

    function fetchData() {
      return new Promise((resolve) => {
        setTimeout(() => {
          const items = Array.from({ length: 10 }, (_, i) => `Item ${Date.now()} - ${i + 1}`);
          resolve(items);
        }, 1000);
      });
    }

    function appendItems(items) {
      const container = document.getElementById('content');
      items.forEach(item => {
        const div = document.createElement('div');
        div.textContent = item;
        container.appendChild(div);
      });
    }

    function showLoader(show) {
      document.getElementById('loader').style.display = show ? 'block' : 'none';
    }

    window.addEventListener('scroll', debounce(() => {
      if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
        loadMoreContent();
      }
    }, 200));

    function debounce(func, delay) {
      let timeout;
      return function (...args) {
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(this, args), delay);
      };
    }

    // Load initial content
    loadMoreContent();
  </script>
</body>

FAQs

Q: Can I use this with real APIs?
Yes! Replace fetchData() with a real fetch() call or API integration.

Q: Is this better than pagination?
It depends. Infinite scroll is ideal for mobile and social feeds. Pagination is better for SEO and precise navigation.

Q: Can I use this in frameworks like React or Vue?
Absolutely. The logic remains similar—you just manage state and DOM differently.

Q: How do I stop loading after all items are fetched?
You can use a flag like hasMoreData and conditionally skip fetching when false.

Conclusion

Infinite scroll is a powerful UX feature, and you don’t need big libraries to use it. With just a few lines of JavaScript, you can deliver seamless, app-like browsing. Whether you’re building a blog, portfolio, or product listing—this technique keeps users engaged without ever clicking “Next”.

One Reply to “Master Infinite Scroll in JavaScript with Just a Few Lines of Code”

Leave A Comment