ankur
ankur

Reputation: 4733

On scroll load data on demand

I am implementing on demand loading of data through scrolling.

I have register the function in document.ready for a div.

The data should only be populated once the scroll is reached to the last. so to identify whether the scroll has reached till the last i am using the below function.

$("#tree").scroll(function () {
                if (isScrolledToBottom(this)) {
                    
                }
            });

But the function is not returning the correct value. What I mean is it should return the a true value when scroll has reached to its last.

function isScrolledToBottom(object) {
            return ($(object).attr('scrollHeight') - $(object).scrollTop() - 1) <= $(object).height();
        };

Upvotes: 0

Views: 4298

Answers (3)

JBelfort
JBelfort

Reputation: 123

 var scrollHeight = $(object).prop("scrollHeight"); // total scrollable height of the element 
    var scrollTop = $(object).scrollTop(); // how far you have come from the top while scrolling vertically
    var height =  $(object).height(); // the constant height of the portion in display at all times

    if (scrollHeight === (scrollTop + height)) {
        //console.log("fetching page");
        fetchNextPage();
    }

Upvotes: 0

Dutchie432
Dutchie432

Reputation: 29160

If you want to do infinite scrolling, check out my answer here: How to load the web page content based on user scrolling

This demo is triggered at a certain Y scroll position. If you are looking to accomplish this specifically when a user reaches a certain item, you might want to look at the Waypoints plugin.

http://imakewebthings.com/jquery-waypoints/

Infinite scroll Demo: http://imakewebthings.com/jquery-waypoints/infinite-scroll/

$('.theItems:last').waypoint(function(event, direction) {
    //Ajax fetch here
});

Upvotes: 1

Alytrem
Alytrem

Reputation: 2620

Try this instead :

return ($(object).attr('offsetHeight') + $(object).attr('scrollTop') >= $(object).attr('scrollHeight'));

Upvotes: 1

Related Questions