Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
195
rated 0 times [  198] [ 3]  / answers: 1 / hits: 16790  / 8 Years ago, fri, august 5, 2016, 12:00:00

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


More From » jquery

 Answers
13

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>




[#61127] Wednesday, August 3, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
loganl

Total Points: 424
Total Questions: 86
Total Answers: 112

Location: Zimbabwe
Member since Thu, Jul 21, 2022
2 Years ago
;