Reputation: 9439
I have this code for loading data. When user scrolls down over a half of screen, it continues to load data and append HTML to document. The problem is $(window).height() doesn't update on the fly after HTML changes
so the condition expression goes wrong. How to fix it?
// Check scrollbar is down a half.
$(window).scroll(function() {
console.log("flag: " + flag);
console.log($(window).scrollTop());
console.log($(window).height());
if (($(window).scrollTop() > $(window).height() / 2)) {
if(flag == 0) {
console.log("Load data");
loadData(globalIndex, globalCount);
globalIndex += 40;
}
flag = 1;
} else {
flag = 0;
}
});
Upvotes: 1
Views: 185
Reputation: 15366
$(window).height()
will give you the browser's height (which is constant unless you resize your window). Try using:
$(document).height() - ($(window).height()/2);
instead...
Upvotes: 1
Reputation: 91
The height of your window isn't going to change unless you resize the browser screen. The problem with your formula is that in order to make it work, you'll need to load enough data to move your scrollbar back above the midpoint. If you don't, this formula will constantly return true, and you'll be calling loadData far more times than you care to.
As a potential workaround (depending on how long it takes to load your data), you can call loadData once your scrollbar reaches the bottom of your window. This condition will be true far less frequently than your current one, and it will only load data if your user is attempting to view it. If data loading is quick, then this is an easy solution. If it is a time-intensive process, and that's the reason you chose to load data once you got to the halfway point, then consider loading more data at a time and including a spinner or some other visual clue to inform the user that data is loading.
Upvotes: 2