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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With