Reputation: 1821
I need to calculate the end of scrolling on web page so that i can make an Ajax call. I have searched posts in stackoverflow, but the solutions didn't worked for me.
I am using the below code ion order to determine that:
$(window).scrollTop() == $(document).height() - $(window).height()
but the above condition fails and am not able to get to know when page scroll ends.
As the values don't match on L.H.S and R.H.S the condition fails. Just in order to check i used:
$(window).scrollTop() == $(document).height() - $(window).height() - 13
which works for chrome and firefox but fails for IE. I need a concrete solution and don't want to hard code values. Please help me in getting it right.
EDIT: To be specific, i am trying to calculate the end of vertical scroll bar.
Upvotes: 6
Views: 4292
Reputation: 1514
Here is what I would do:
$(window).on('scroll', function() {
if($(window).scrollTop() != 0)
{
if( $(window).height() + $(window).scrollTop() >= $(document).height() )
{
//YES, I AM EXACTLY AT THE END OF THE SCROLL, PLZ FIRE AJAX NOW
}
}
});
CAUTION: Be very careful about having negative top margins though for styles in any of your elements on the page!! it may offset the calculation!
Upvotes: 3
Reputation: 318182
Here's how you do it. You take the scrolled distance and add the window height, then check if they equal the document height :
$(window).on('scroll', function() {
if (($(this).scrollTop() + $(this).height()) - $(document).outerHeight(true) >= 0) {
alert('Scrolled to bottom');
}
});
This works for me in all five browsers!
Upvotes: 0
Reputation: 347
This should retrieve the page height for you (not using jQuery but javascript instead):
var height = document.body.clientHeight;
You will find that this is the best cross-browser solution to your problem.
Upvotes: 1