Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Infinite Scroll inside a div

I am trying to create an infinite loading page with the use of javascript. I found this: How to do infinite scrolling with javascript only without jquery

I have been playing with the last answer that links to this jsfiddle page: http://jsfiddle.net/8LpFR/

 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 - 10) {
          var newDiv = document.createElement("div");
          newDiv.innerHTML = "my awesome new div";
          document.getElementById("scroll-content").appendChild(newDiv);
          checkForNewDiv();
      }
 }; 
 checkForNewDiv();

How would I modify that in order to make the scrolling work inside a div rather than as the whole page? As in, what would lastDivOffset and pageoffset change to?

like image 642
Jacob Avatar asked Jun 30 '26 08:06

Jacob


2 Answers

Simplest of them all.

var scrollY = container.scrollHeight - container.scrollTop;
var height = container.offsetHeight;
var offset = height - scrollY;

if (offset == 0 || offset == 1) {
    // load more content here
}
like image 144
TheRealChx101 Avatar answered Jul 02 '26 23:07

TheRealChx101


Here is the solution without creating any new wrapper division.

document.getElementById("scroll-content").addEventListener("scroll", function(event) {
  var newDiv = document.createElement("div");
  newDiv.innerHTML = "my awesome new div";
  document.getElementById("scroll-content").appendChild(newDiv);
});

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

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

checkForNewDiv();

JSFIDDLE DEMO

like image 27
Suresh Ponnukalai Avatar answered Jul 02 '26 23:07

Suresh Ponnukalai