Reputation: 399
I'm trying to create a scroller which loads content when the user nears the bottom of an element however I'm struggling with calculating the current distance from the bottom of the element #grid
when the user scrolls.
$(window).scroll(function (event) {
var scroll = $(window).scrollTop();
var div = $('#grid');
var bottom = ((div.offset().top + div.height()) - scroll);
$('.scroll').html(bottom);
});
The .scroll
element displays the value although it doesn't seem to be giving correct numbers. Any ideas, I've come to a stand still. I seem to be getting the distance from the top of the window to the bottom of the container, not from the current scroll position?
Top of page
Scrolled down
Upvotes: 3
Views: 3470
Reputation: 337560
You need to add the height of the window too.
$(window).scroll(function (event) {
var scrollBottom = $(window).scrollTop() + $(window).height();
var div = $('#grid');
var bottom = ((div.offset().top + div.height()) - scrollBottom);
$('.scroll').html(bottom);
});
If bottom
is negative by less than the window height, then the bottom of the #grid
div is visible on the screen.
Upvotes: 2