Simple Infinite Scroll with PURE Javascript – Free Download!

Welcome to a tutorial on how to create an infinite page scroll with vanilla Javascript. If you have been following up with social media – Facebook, Twitter, Instagram, etc… Then you should not be a stranger to that “scroll down to load more contents” interface. Yep, that is exactly what we will walk through in this guide – An example of infinite scroll using only pure Javascript. Read on!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

TABLE OF CONTENTS

Download & Notes Infinite Scroll Useful Bits
Tutorial Video The End

 

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICKSTART

  1. If not using PHP, change endless.url in 2-iscroll.js section A to your own server-side script.
  2. Launch 1-iscroll.html in the browser.
  3. Captain Obvious – Use http:// not file://.

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

INFINITE SCROLL

All right, let us now get into creating a simple endless scroll with Javascript.

 

STEP 1) CONTENT PAGE

1-iscroll.html
<!-- (A) CONTENTS WRAPPER -->
<div id="page-content"></div>
 
<!-- (B) JUST SOME COSMETICS FOR DEMO -->
<style>
#page-content { background: lightblue; }
.page-demo { height: 1600px; }
</style>

That’s all, as straightforward as can be. We only need a <div id="page-content"> wrapper to load the contents into.

 

 

STEP 2) INFINITE SCROLL JAVASCRIPT

2-iscroll.js
var endless = {
  // (A) PROPERTIES
  url : "3-dummy.php", // CHANGE THIS TO YOUR OWN!
  first : true, // LOADING FIRST PAGE?
  proceed : true, // OK TO LOAD MORE PAGES? "LOCK" TO PREVENT LOADING MULTIPLE PAGES
  page : 0, // CURRENT PAGE
  hasMore : true, // HAS MORE CONTENT TO LOAD?
 
  // (B) INITIALIZE INFINITE SCROLL
  init : function () {
    // (B1) LISTEN TO END OF PAGE SCROLL - LOAD MORE CONTENTS
    window.addEventListener("scroll", function () {
      if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) {
        endless.load();
      }
    });
 
    // (B2) LOAD INITIAL PAGE
    endless.load();
  }, 
 
  // (C) AJAX LOAD CONTENT
  load : function () { if (endless.proceed && endless.hasMore) {
    // (C1) ENSURE ONLY 1 PAGE CAN LOAD AT ONCE
    endless.proceed = false;

    // (C2) PAGINATION & POST DATA
    var data = new FormData(),
        nextPg = endless.page + 1;
    data.append("page", nextPg);
    // APPEND MORE OF YOUR OWN DATA IF YOU WANT
    // data.append("KEY", "VALUE");
 
    // (C3) AJAX LOAD CONTENT
    var xhr = new XMLHttpRequest();
    xhr.open("POST", endless.url);
    xhr.onload = function () {
      // (C3A) NO MORE CONTENT
      if (this.response == "END") { endless.hasMore = false; }

      // (C3B) APPEND CONTENT INTO HTML WRAPPER
      else {
        var el = document.createElement("div");
        el.innerHTML = this.response;
        document.getElementById("page-content").appendChild(el);
        endless.proceed = true; // UNLOCK
        endless.page = nextPg; // UPDATE CURRENT PAGE

        // (C3C) FIRST PAGE ONLY - MAKE SURE CONTENT COVERS WINDOW HEIGHT
        if (endless.first) {
          if (document.body.scrollHeight <= window.innerHeight) { endless.load(); }
          else { endless.first = false; }
        } else { endless.first = false; }
      }
    };
    xhr.send(data);
  }}
};
window.addEventListener("DOMContentLoaded", endless.init);

This may look confusing at first, but keep calm and look carefully. There are only 2 functions here!

  1. Just a bunch of settings and flags.
  2. init() loads on DOM content ready, and initializes the endless scroll.
    • Attach a page scroll listener, run endless.load() if the page hits the bottom.
    • Run endless.load() to load the first page from the server.
  3. load() will get content from the server via AJAX, and append it into <div id="page-content">.
    • Take note of how the endless.proceed flag is used here – Since AJAX is asynchronous, we need a “lock” to ensure only one page is loading at a time.
    • Also, take note of this.response == "END". The server can respond END to stop the infinite scroll.
    • The rest are pretty much “standard AJAX fetch content”.

 

 

STEP 3) SERVER-SIDE CONTENT

3-dummy.php
<?php
// (A) NO MORE CONTENT TO SERVE
if ($_POST['page']==5) { echo "END"; }

// (B) SERVE DUMMY PAGE
else { echo "<div class='page-demo'>PAGE ".$_POST['page']."</div>"; } ?>

Lastly, this is just a dummy server-side script – Output whatever content you are working on, with whatever language you are using. Things to take note of:

  • The Javascript will POST a page over, use this to do pagination as required.
  • Output END if there is nothing left to show.

 

 

USEFUL BITS

That’s the end of the tutorial, and here are a few extras that you may find useful.

 

INFINITE SCROLLING – REALLY?

Technically, we can load and serve an infinite amount of content this way. But you have to consider that computers still have finite memory and system resources… Plus, do you really have that much content to serve? So even though this is called “infinite scroll”, there still has to be a limit in order to prevent browser crashes.

 

NOTE – BAD FOR SEO

Also, a piece of bad news for you SEO lovers. Even though some search engines are smart enough to understand AJAX calls, they may not “scroll down” to load more contents; Infinite scrolling is only good for certain types of content, and please do not use it to “hide” your useful content… For example, “scroll down to read more” for an article. You will end up on the bad side of SEO practice.

 

TUTORIAL VIDEO

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to build a better project, and if you have anything to add to this guide, please feel free to comment below. Good luck and happy coding!

14 thoughts on “Simple Infinite Scroll with PURE Javascript – Free Download!”

  1. Jimmy Raymond belanger

    Any idea to get document.getElementById after the ajax load ?
    We are unable to find id after ajax load …

    1. Sorry, I don’t quite catch your question. The above example is already doing document.getElementById("page-content").appendChild(el) on AJAX load.
      If you are getting “cannot find element” errors, that is probably because you have assigned the wrong ID.

  2. Thank you !
    Your script is working very well.
    You can check the result on : LINK REMOVED => https://code-boxx.com/faq/#nolink

    I have made some modification to your scripts for my needs.
    1. Use the entire url because if you have your scripts on several pages with SEO directives like dash in the url it can generate a directory error.
    xhr.open(‘POST’, “https://www.completeurl.com/ajax-page.php”);

    2. I don’t know why but on full hd screens it is unable to detect that the user is at the bottom of the page completely. I just put -4000 for sure we load but you can try with – 500
    if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight – 4000) { endless.load(); }

    3. I post the width of the visitor’s screen in the post that allows me to push div the correction according to the width.
    width = window.screen.width;
    data.append(‘width’, width);

    Great Script thx for your help 🙂

  3. Mattijs Snepvangers

    Hi!,
    First of all, I love you site! Straight, clear and usable for beginners and advanced codes alike!
    I was wondering, would it be possible to ‘semi-scroll’ through e.g. previousPage/currentPage/nextPage and shift/replace them depending on which way the user scrolls? That way you might be able to achieve true infinite scrolling (depending on content of course 😉 ). I’m not an ES-professional but in theory it sounds feasable…

    1. That is called “lazy pagination” then. Load the next page when user hits the bottom, load last page if hits the top. Problem is, what if the page content does not fill up the entire height of the screen?

  4. Nice tutorial!
    I’ve tried the script: it works perfectly on Firefox, while on Chrome 49 and Opera 36 (I need to support old browsers) only initial contents are loaded and nothing happens when I scroll the page. I don’t know why.

      1. It’s clear that it depends on “listen” function.
        I’m using the following code (it works with every browser I’ve tested it):

        listen: function() {
        if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) {
        endless.load();
        }
        };

      2. Thanks for sharing! documentElement, offsetHeight, scrollTop should be well-supported from IE 8 and onwards… So anyone who is working with the ancient browsers – Take note.

  5. Thanks,
    After doing lots of googling. At last I came to a solution to give a try. I have read and understood this post bro. I typically think this is the way to go given the fact impressive design is a big part of user satisfaction in this day and age.

Leave a Comment

Your email address will not be published. Required fields are marked *