Reputation: 44293
I know there are multiple plugins out there however I wonder how I can make my own thing work the way I want.
First off, when scrolling to the bottom of my page I want to trigger a function called ajaxLoadActivity
which is now triggered with a "Show More" button.
$(window).scroll(function() {
if ( $(window).scrollTop() >= ( $(document).height() - $(window).height() ) )
if ( $('ol.astream > .loadCount:last > li').attr('id') == "noMoreActivities" )
return false;
ajaxLoadActivity('bottom', true);
console.log('fired');
});
I have the problem that probably everybody encounters when trying to do this himself. The problem is that the function is fired multiple times. The function ajaxLoadActivity
does all the ajax stuff and appends <li>
items to an existing <ol>
. The function works perfect when just using it with the "Show More" Button.
However I wonder how I can trigger the same function when simply scrolling to the bottom of the page. But I want to call it only once - then wait till the stuff is loaded - and only then allow the function to be fired again if the bottom is reached again.
And I have an exception that is already in my sample code above … if my last element has an id of noMoreActivities
I don't want the function to be fired again, because then there are no more activities.
Any ideas how I can fire the function only once and wait till the request happend?
Upvotes: 4
Views: 5851
Reputation: 641
$(window).scrollTop() == ( $(document).height() - $(window).height() ) will make it execute the call only once. Try it.
Upvotes: 0
Reputation: 13812
Assuming you're using $.post
you can return it in your ajaxLoadActivity
function then check to see if it's running
var ajax;
$(window).scroll(function() {
if ( $(window).scrollTop() >= ( $(document).height() - $(window).height() ) )
if ( $('ol.astream > .loadCount:last > li').attr('id') == "noMoreActivities" )
return false;
if (ajax) {
return false; // don't make another request, let the current one complete, or
// ajax.abort(); // stop the current request, let it run again
}
ajax = ajaxLoadActivity('bottom', true);
console.log('fired');
});
function ajaxLoadActivity(one, two) {
return $.post(/* stuff */);
}
Upvotes: 1