I have an annoying little issue here. I have code which loads content from page2 and appends it to #content. That works, but sometimes it happens twice, then appends page3 before page2. Thats because in page3, there is just one post, but in page2, 4 posts.
How can I make my code wait until the append finishes to run again? Here’s my code:
$(window).scroll(
function(){
if(browserName != "safari") {
var curScrollPos = $('html').scrollTop();
}
else {
var curScrollPos = $('body').scrollTop();
}
if(curScrollPos > 218) {
$("#sidebar").addClass("open");
}
if(curScrollPos < 218) {
$("#sidebar").removeClass("open");
}
var scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();
if(scrollBottom == 0) {
if(home != 0 || search != 0 || category != 0) {
if(currentPage < numPages) {
$("#main .loader-posts").fadeIn();
currentPage++;
if(search == 1) {
var getPostsUrl = "page/"+currentPage+"/?s="+searchTerm;
}
else {
var getPostsUrl = "page/"+currentPage;
}
$.get(getPostsUrl, function(data) {
$("#main .loader-posts").fadeOut(
'slow',
function(){
var newPosts = $(data).find("#content").html();
$("#content").append(newPosts);
$('#container.tiles').masonry('reload');
});
});
}
}
else {
}
}
Add a variable that keeps track of whether you are loading the next page or not and then only load if you are not currently loading something else. This is the root of your problem.
.scroll()may fire twice before the next section is loaded, and as long ascurrentPage < numPagesit will incrementcurrentPageand load again. And, because.get()is asynchronous, you are not guaranteed to finish the first.get()request before any subsequent request. Adding aloadingstate fixes this.