I'm working on making an infinite scroll function for a page and am running into an issue where it appears that the $( window ).scroll() function is firing twice. I've seen similar questions on stackoverflow, but they seem to be related to fast scrolls and not having something in place to check weather the request has already been sent. Here's the code that I'm working with right now, I imagine that its something easy that I'm missing here.
var loading = false;
var scrollcount = 0;
$( window ).scroll( function(){
scrollcount++;
var scrolling = $( document ).scrollTop();
var position = $( "#ajax-load" ).offset();
if( scrolling + $( window ).height() > position.top - 200 && loading == false ){
console.log( loading ); //returns 2 falses
console.log( scrollcount ); //returns 2 of the same number
console.log( $( document ).scrollTop() ); //returns same number
loading = true;
$( "#ajax-load" ).css( "display", "block" );
$.get( "url/to/my/script", info )
.done( function( data ){
//here's where the items are appended to the document
setTimeout( function(){
loading = false;
}, 5000 );
});
}
});
The face that when I log out the scrollcount variable and the return from scrollTop() I get the same number twice seems to tell me that the event is actually firing twice at the same time for some reason. It seems that if it were firing twice, one after the other, the loading variable would be set to false and not fire that second time. Like I said, I imagine that it's something super simple that I'm missing. Thanks for your help!