Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if ($(window).scrollTop() == $(document).height() - $(window).height() - 300) Why this not work?

I have problem with my infinite scroll. I want execute load more before 300px of the bottom of the page.

I detect the scroll with :

$window.scroll(function(){

And in this function I have test this :

if (($document.height() - $window.height()) == $window.scrollTop()) {

But this works only when we are at footer.

Then I test this :

if ($(window).scrollTop() >= $(document).height() - $(window).height() - 300)

But the infinite scroll run several times between 300px and the bottom of the page.

After this, I want just test this :

if ($(window).scrollTop() == $(document).height() - $(window).height() - 300)

But this not working and I don't understand. Do you have ideas ?

Thanks you so much

like image 508
Rémi Bonnet Avatar asked Dec 24 '22 03:12

Rémi Bonnet


1 Answers

The condition to check is simply:

if($(window).scrollTop() + $(window).height() > $(document).height() - 300){}

Probably == or === might not work because it wont hit exact equal to condition.

Edit: As requested I have added the code to prevent multi-calling the page load function. What happens is simple unbind of the event till the new content is loaded. Once it is completed the event is bound back again. So, you can use > and still the load function is only called once. I have created a simple setTimeout to simulate the delay from ajax request inside in your code.


---LINK TO FIDDLE---


SEE THIS SIMPLE WORKING DEMO:

var winCached = $(window),
  docCached = $(document)

var currLeng = 0;

function addContent() {
  dettachScrollEvent();
  setTimeout(function() { //this timeout simulates the delay from the ajax post
    for (var i = currLeng; i < currLeng + 100; i++)
      $('div').append(i + '<br />');
    currLeng = i;
    console.log("called loader!");
    attachScrollEvent();
  }, 500);

}

function infiNLoader() {
  if (winCached.scrollTop() + winCached.height() > docCached.height() - 300) {
    addContent();
    //alert("near bottom! Adding more dummy content for infinite scrolling");
  }
}

function attachScrollEvent() {

  winCached.scroll(infiNLoader);
}

function dettachScrollEvent() {
  winCached.unbind('scroll', infiNLoader);
}
addContent();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
like image 139
Iceman Avatar answered Jan 19 '23 00:01

Iceman