Simple Infinite Scroll with Javascript – Free Code 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
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

For you guys who just want to use this as a “plugin”:

  1. Change endless.url in 2-scroll.js to your own server-side script.
  2. In your HTML page – Create a <div id="page-content"> and <div id="page-loading">. Also, load 2-scroll.js.
  3. The Javascript will POST a page number to your server-side script, use it to load whatever content, and output it. If there is nothing left to load, just output END.
  4. 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

THE HTML

1-scroll.html
<!-- (A) CONTENTS -->
<div id="page-content"></div>
 
<!-- (B) NOW LOADING -->
<div id="page-loading">Now loading...</div>

This HTML should be very straightforward.

  • <div id="page-content"> is where the contents will be loaded via AJAX.
  • <div id="page-loading"> is a simple “now loading” message that will show whenever the content is being fetched from the server. Feel free to use your own AJAX spinner image if you want.

 

THE CSS

1-scroll.css
#page-content, #page-loading { 
  padding: 10px;
  background: #dffcd1;
}
#page-loading { display: none; }
html, body { font-family: arial, sans-serif; }

Just a bunch of simple cosmetics. The only functional part here is hiding the “now loading” by default – #page-loading { display: none; }.

 

 

STEP 2) INFINITE SCROLL MECHANICS

THE JAVASCRIPT

2-scroll.js
var endless = {
  // (A) PROPERTIES
  // (A1) SETTINGS
  url: "3-contents.php", // URL to load content from
  // (A2) FLAGS
  page: 0, // current page
  hasMore: true, // has more contents to load?
  proceed: true, // safe to load more? another page currently loading?
  first: true, // is this the first loading cycle?
  // (A3) HTML ELEMENTS
  eLoad: null, // now loading
  eContent: null, // where to load contents into
 
  // (B) INIT
  init: function () {
    // (B1) GET HTML ELEMENTS
    endless.eLoad = document.getElementById("page-loading");
    endless.eContent = document.getElementById("page-content");
 
    // (B2) ATTACH SCROLL LISTENER
    // CREDITS: https://stackoverflow.com/questions/9439725/javascript-how-to-detect-if-browser-window-is-scrolled-to-bottom
    window.addEventListener("scroll", function(){
      if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) {
        endless.load();
      }
    });
 
    // (B3) LOAD CONTENTS
    endless.load();
  },
 
  // (C) AJAX LOAD CONTENTS
  load: function () { if (endless.proceed && endless.hasMore) {
      // (C1) BLOCK MORE LOADING UNTIL THIS LOAD CYCLE IS DONE
      endless.proceed = false;

      // (C2) SHOW NOW LOADING
      endless.eLoad.style.display = "block";
 
      // (C3) DATA
      var data = new FormData(),
      nextPg = endless.page + 1;
      data.append('page', nextPg);
 
      // (C4) AJAX
      var xhr = new XMLHttpRequest();
      xhr.open("POST", endless.url);
      xhr.onload = function () {
        // NO MORE CONTENTS TO LOAD
        if (this.response == "END") {
          endless.eLoad.innerHTML = "END";
          endless.hasMore = false;
        }

        // PUT CONTENTS INTO HTML
        else {
          var el = document.createElement('div');
          el.innerHTML = this.response;
          endless.eContent.appendChild(el);
          endless.eLoad.style.display = "none";
          endless.page = nextPg;
          endless.proceed = true;

          // (C5) ON INIT ONLY
          // LOAD MORE IF CONTENTS DID NOT HIT THE END OF WINDOW
          if (endless.first && endless.hasMore) {
            if (document.body.scrollHeight <= window.innerHeight) { endless.load(); }
            else { endless.first = false; }
          } else { endless.first = false; }
        }
      };
      xhr.send(data);
    }
  },
};
window.addEventListener("DOMContentLoaded", endless.init);

 

 

THE EXPLANATION

Not going to explain line-by-line, but essentially:

  • A – A bunch of settings and flags.
  • B – Initialize the endless scroll on page load.
    • Fetch <div id="page-content"> and <div id="page-load">.
    • 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.
  • C – Load content from the server via AJAX, and append it into <div id="page-content">.

 

STEP 3) SERVER-SIDE CONTENT

3-contents.php
<?php
if ($_POST['page']==5) {
  echo "END"; // ECHO END IF NO MORE CONTENTS TO LOAD
} else {
  echo "<div style='height:800px;'>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:

  • 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 contents… For example, “scroll down to read more” for an article. You will end up on the bad side of SEO practice.

 

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 Javascript – Free Code 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();
        }
        };

        1. 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 *