monkee
monkee

Reputation: 399

Calculating pixels from bottom of element

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

enter image description here

Scrolled down

enter image description here

Upvotes: 3

Views: 3470

Answers (1)

Rory McCrossan
Rory McCrossan

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

Related Questions