SimonLeCat SimonLeCat - 7 days ago 6
Javascript Question

Lazy Load and infinitive scrolling issue in jQuery to find new height of an element with position absolute?

I have a div element with position absolute and overflow scroll like this:

<style>
.sevencov {
position: absolute;
width: 61.333%;
left: 16.667%;
top: 46px;
bottom: 0;
right: 0;
overflow: auto;
}
</style>

<div class="sevencov">
<a id="load-more" class="load-more" title="Load More" onclick="myFunction()"></a>
</div>


I want to fire the load more button at a certain % of the div on scroll, using jQuery I tried this:

$(function () {
var prevHeight = $('.sevencov').height();
$('.sevencov').scroll(function () {
var curHeight = $(this).height();
if ($(this).scrollTop() > ($(document).height() - curHeight)*44) {
$('#load-more').click();
}

});
});


But the problem is that it fires multiple times because the height of my div
sevencov
is always the same and I'm not able to find a solution, what am I doing wrong?

Answer

This is called as Lazy Loading

You can play with scrollTop, innerHeight and scrollHeight as below.

Documentation

scrollTop - Get the current vertical position of the scroll bar for the element

innerHeight - Get the current computed inner height (including padding but not border) for the element

scrollHeight - The height of an element's content, including content not visible on the screen due to overflow

In the below snippet, you can place your ajax call.

Also, the below snippet had window.loadProfile = loadProfile; to make sure your inline onclick works with the parameters onClick="loadProfile(184, '', 'user69')". If possible, you can replace this with jquery click event like, $('#load-more').on('click', function(){ /* ajax call */ });

$(function () { 
  
    var testContent = 'The quick brown fox jumps over the lazy dog. ';
  var increment = 20;
  var contentLoading = false;
  var sevencovDiv = $('.sevencov');
  
  function loadProfile(id, text, user) {
    // You can do a ajax call here instead of a below code
    for(var i = 0; i < increment; i++) {
      sevencovDiv.html(sevencovDiv.html() + testContent);
    }
    
    contentLoading = false; // make this false once the content loaded from ajax call
  }
  
  loadProfile();
  
  window.loadProfile = loadProfile;

    $('.sevencov').scroll(function () {                  
      if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
        if(!contentLoading) {
          //loadMore();
          contentLoading = true;
          $('#load-more').click();
        }
    }

    });
});
.sevencov {
    position: absolute;
    width: 61.333%;
    left: 16.667%;
    top: 46px;
    bottom: 0;
    right: 0;
    overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sevencov">
  <a id="load-more" class="load-more" title="Load More" onClick="loadProfile(184, '', 'user69')"></a>
</div>

Comments