How to do infinite scrolling with javascript only without jquery

first of all i don't think that you have to support netscape and ie6 anymore. So with that in mind I created following script

document.addEventListener("scroll", function (event) {
    checkForNewDiv();
});

var checkForNewDiv = function() {
    var lastDiv = document.querySelector("#scroll-content > div:last-child");
    var lastDivOffset = lastDiv.offsetTop + lastDiv.clientHeight;
    var pageOffset = window.pageYOffset + window.innerHeight;

    if(pageOffset > lastDivOffset - 20) {
        var newDiv = document.createElement("div");
        newDiv.innerHTML = "my awesome new div";
        document.getElementById("scroll-content").appendChild(newDiv);
        checkForNewDiv();
    }
};

also see jsfiddle


What about replacing this line of code:

if (getDocHeight() == getScrollXY()[1] + window.innerHeight)

with the following:

if (getDocHeight() - 20 <= getScrollXY()[1] + window.innerHeight) 

Where 20 is the number how much pxs from bottom you want the trigger to execute.

Fiddle


I use requestAnimationFrame instead of listening for scroll. I also added a throttle based on time so it doesn't overwork our page and batched the element additions:

var numElementsToAdd = 10,
    offsetForNewContent = 20;

function checkInfiniteScroll(parentSelector, childSelector) {
  var lastDiv = document.querySelector(parentSelector + childSelector),
      lastDivOffset = lastDiv.offsetTop + lastDiv.clientHeight,
      pageOffset = window.pageYOffset + window.innerHeight;

  if(pageOffset > lastDivOffset - offsetForNewContent ) {
    for(var i = 0; i < numElementsToAdd; i++) {
      var newDiv = document.createElement("div");
      newDiv.innerHTML = "my awesome new div";
      document.querySelector(parentSelector).appendChild(newDiv);
    }
    checkInfiniteScroll(parentSelector, childSelector);
  }
};

var lastScrollTime = Date.now(), 
    checkInterval = 50;

function update() {
  requestAnimationFrame(update);

  var currScrollTime = Date.now();
  if(lastScrollTime + checkInterval < currScrollTime) {
    checkInfiniteScroll("#scroll-content", "> div:last-child");
    lastScrollTime = currScrollTime;
  }
};

update();
  #scroll-content > div {
      background: #c0c0c0;
      height: 40px;
      margin-bottom: 5px;
  }
<div id="scroll-content">
    <div>test div</div>
</div>

Demo

Tags:

Javascript