Search code examples
javascripthtmlcssscroll

How do I make Infinite Scroll to top with js?


There is an example of infinite scroll to bottom.

  var $ol = document.querySelector("ol");
    
    function load_more() {
      var html = "";
      
      for (var i = 0; i < 5; i++) html += '<li></li>';
      $ol.innerHTML += html;
    }
    
    $ol.addEventListener("scroll", function() {	
      if ($ol.scrollHeight - $ol.scrollTop === $ol.clientHeight) 
        load_more();
    });
    <ol>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
    </ol>


  

There is an jsfiddle example

How do I make infinite scroll like this but to top with js?


Solution

  • With $ol.scrollTop === 0 you can check if the ol is scrolled to the top. scollTop is always 0 when in the most upper position.

    Also changed the loadMore function so it appends the new element to the start of the element with $ol.prepend(document.createElement('li'))

    Last I added $ol.scrollTop = firstEl.offsetTop; in the loadmore function to automaticly scroll to the element that was previously the first element.

    I reversed your OL so it's easier to see new items are loaded. This is not necessary of course.

    var $ol = document.querySelector("ol");
    
    //Call this function onload so new content gets loaded and scrolling upwards become available.
    load_more();
    
    //Add event listner that triggers function when the element is scrolled to the top.
    $ol.addEventListener("scroll", function() {
      if ($ol.scrollTop === 0)
        load_more();
    });
    
    //Load more items.
    function load_more() {
      //Get the current first element.
      var firstEl = $ol.firstElementChild;
    
      //prepend the new elements.
      for (var i = 0; i < 5; i++) {
        $ol.prepend(document.createElement('li'))
      }
    
      //scroll to the previous first element.
      $ol.scrollTop = firstEl.offsetTop;
    }
    ol {
      height: 100px;
      overflow: scroll;
    }
    <ol reversed>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
      <li></li>
    </ol>