Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do an infinite scroll in plain Javascript

I want to avoid using jQuery or another library for the sake of keeping my code minimal, I need very little in the way of features, I just want to append to a list when the user scrolls to the bottom. How would I do this in plain Javascript?

like image 202
Abhinav Sharma Avatar asked Sep 10 '25 18:09

Abhinav Sharma


2 Answers

Basicaly you just need to hook the event scroll, check if the user scrolled down enough and add some content if so:

<html><body>
<div id="test">scroll to understand</div>
<div id="wrapper" style="height: 400px; overflow: auto;">
  <div id="content"> </div>
</div>

<script language="JavaScript">
  // we will add this content, replace for anything you want to add
  var more = '<div style="height: 1000px; background: #EEE;"></div>';

  var wrapper = document.getElementById("wrapper");
  var content = document.getElementById("content");
  var test = document.getElementById("test");
  content.innerHTML = more;

  // cross browser addEvent, today you can safely use just addEventListener
  function addEvent(obj,ev,fn) {
    if(obj.addEventListener) obj.addEventListener(ev,fn,false);
    else if(obj.attachEvent) obj.attachEvent("on"+ev,fn);    
  }

  // this is the scroll event handler
  function scroller() {
    // print relevant scroll info
    test.innerHTML = wrapper.scrollTop+"+"+wrapper.offsetHeight+"+100>"+content.offsetHeight;

    // add more contents if user scrolled down enough
    if(wrapper.scrollTop+wrapper.offsetHeight+100>content.offsetHeight) {
      content.innerHTML+= more;
    }
  }

  // hook the scroll handler to scroll event
  addEvent(wrapper,"scroll",scroller);
</script>
</body></html>
like image 197
Jan Turoň Avatar answered Sep 12 '25 10:09

Jan Turoň


For achieving this behaviour you don't need jQuery or a jQuery plugin. You can use only CSS or JavaScript (if you want to cover all browsers).

But don't use onScroll: you can do all of this with just vanilla JS and the Intersection Observer API.

All you need to do is place elements and listen for when they become available in the screen. The Intersection Observer API is very customisable to fit all your needs.

In summary: you accomplish that with a few JavaScript & HTML lines and it's much more performant than listening for scroll events in the browser.

like image 25
Jose Greinch Avatar answered Sep 12 '25 09:09

Jose Greinch