I have made a jQuery script that loads items from the database when the user scrolls. Only problem is that when a user scrolls very quickly after page load the result of the script doubles up so the information from the database is shown twice. Not really sure what’s going on here but the script is below. It’s all on doc ready by the way.
function last_item_funtion()
{
var ID=$(".newsItem:last").attr("id");
$('#feedLoader').html('<img src="../files/images/bigLoader.gif" style="display:block;margin-left:auto;margin-right:auto;">');
$.post("AJAX/scroll_feed.php?action=get&last_item_id="+ID,
function(data){
if (data != "") {
$(".newsItem:last").after(data);
}
$('#feedLoader').empty();
});
};
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
last_item_funtion();
}
});
This isn’t my jsfiddle but it shows in a nutshell what the script does. It doesn’t show the problem I am having but i cannot replicate that as I can’t put a whole database on jsfiddle.
UPDATE
After having a play I have realized that it’s not when the user scrolls straight after page load it’s when the user does one continuous scroll instead of a short one. From this I am guessing that jQuery does not register the data has been loaded until the scroll is stopped.
Well, I guess the
scrollevent is fired multiple times, so the request is done multiple times. Try the following:It binds the
scrollevent, and unbinds it after it is triggered. The event is bound again after the request is finished.(You might also check out jQuery.one(), but I have never used it.)
EDIT:
After doing some testing, the scroll event gets triggered a lot even though we unbind it, so here is an updated example that uses a global variable to tell the
scroll-callback if it’s loading something already, or if it’s ok to do a new post request: