i am trying to build a function that when you scroll to the bottom of the page it runs a function to load in more items on a page.
I started by putting in a div with no content
<div id="loadMore"></div>
and then i found on here another function that looks at the scroll
function isScrolledIntoView(elem)
{
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
console.log(docViewTop, docViewBottom, elemTop, elemBottom);
return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom) && (elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
$(window).scroll(function() {
if(isScrolledIntoView($('#loadMore')))
{
alert("reached");
return false;
}
});
one problem is it seems to alert reached too soon and the other main problem is that it alerts "reached" back to the screen so many times - this is obviously bad because I would only want the function to run once...
then it would load in the other content and if the bottom of the page was reached again then the function (alert in eg) would run again
am i going about this the best way? and can anyone help?
thanks
When working with the scroll function you need to be careful as the event is triggered once for every pixel scrolled. Therefore you need to use a timeout to only call the function when scrolling has stopped. Try this:
Example fiddle
you should bind your function only once. after adding new items to the page u can check if more items are available and rebind this function again.
test it: http://fiddle.jshell.net/d5CSd/