Reputation:
I have a scroll function
$('#lisr').scroll( function() {
if($(this).scrollTop() + $(this).innerHeight()>= $(this)[0].scrollHeight)
{
//DO some code
}
}
The problem is when I scroll down and it hits the bottom it executes the code twice instead of once, so If I make any ajax call in it, it is made twice, what I am missing in it?
Upvotes: 2
Views: 95
Reputation: 1012
The scroll()
function binds to the scroll event - which is fired many times when the user scrolls the page.
Write your code with the assumption that it can be called more than once:
var completed = false;
function doSomeCode() {}
function isAtBottomOfPage() {}
$('#lisr').scroll(function () {
if (!completed && isAtBottomOfPage()) {
doSomeCode();
completed = true;
}
});
jsfiddle: http://jsfiddle.net/kZJ9k/1/
As a more advanced note, you probably shouldn't bind your logic directly to the scroll
event; you run the risk of causing lag for your users when scrolling. Read more about this from John Resig:
http://ejohn.org/blog/learning-from-twitter/
Upvotes: 2
Reputation: 7143
Here are my codes for endless scrolling. What I do is unbinding the scroll event until the ajax request finishes. You can also use a variable as a flag and check/change its value before calling ajax request. Hope it helps:
$(document).ready(function(){
$(window).bind('scroll', loadPage);
});
var loadPage = function(){
if($(window).scrollTop() + $(window).height() == $(document).height()) {
$(window).unbind('scroll');
$.ajax({
//Your things here
success: function(result){
// Do success here
$(window).bind('scroll', loadPage);
},
error : function(xhr){ //Do error here }
});
}
}
Upvotes: 1
Reputation: 7438
$('#lisr').scroll( function() {
if($(this).scrollTop() + $(this).innerHeight() > $(this)[0].scrollHeight)
{
//DO some code
}
}
Upvotes: 0