ChatGPT解决这个技术问题 Extra ChatGPT

jQuery load more data on scroll

I am just wondering how can i implement more data on scroll only if the div.loading is visible.

Usually we look for page height and scroll height, to see if we need to load more data. but the following example is little complicated then that.

Following image is perfect example. there are two .loading div's on the drop down box. When user scroll the content, whichever is visible it should start loading more data for it.

https://i.stack.imgur.com/IKHNl.png

So how can i find out if .loading div is visible to user yet or not? So i can start loading data for that div only.


m
marioosh

In jQuery, check whether you have hit the bottom of page using scroll function. Once you hit that, make an ajax call (you can show a loading image here till ajax response) and get the next set of data, append it to the div. This function gets executed as you scroll down the page again.

$(window).scroll(function() {
    if($(window).scrollTop() == $(document).height() - $(window).height()) {
           // ajax call get data from server and append to the div
    }
});

This solution is great and the simplest ;) You can improve this code with following lines in ajax call: new_element.hide().appendTo('.your_div').fadeIn(); $(window).scrollTop($(window).scrollTop()-1); First line appends elements in nice way, second assures that your function never stops at the bottom of the page.
I approach this in a similar fashion, accounting for the fact that you always have arbitrary stuff (navigation) at the bottom of your page, and you really want to load before you hit the bottom. So my inner function is: var end = $("#BottomThing").offset().top; var viewEnd = $(window).scrollTop() + $(window).height(); var distance = end - viewEnd; if (distance < 300) // do load
Ryan Bates has an excellent episode about this: railscasts.com/episodes/114-endless-page. There is also a revised version but you may need a subscription.
If someone like to know if a user has scrolled to the bottom he can use this if condition inside the if that displayed here: if($(window).scrollTop() + $(window).height() == $(document).height()) { console.log('Scrolled to the bottom !'); }
This answer is not what I have asked in the question.
d
defau1t

Have you heard about the jQuery Waypoint plugin.

Below is the simple way of calling a waypoints plugin and having the page load more Content once you reaches the bottom on scroll :

$(document).ready(function() {
    var $loading = $("<div class='loading'><p>Loading more items&hellip;</p></div>"),
    $footer = $('footer'),
    opts = {
        offset: '100%'
    };

    $footer.waypoint(function(event, direction) {
        $footer.waypoint('remove');
        $('body').append($loading);
        $.get($('.more a').attr('href'), function(data) {
            var $data = $(data);
            $('#container').append($data.find('.article'));
            $loading.detach();
            $('.more').replaceWith($data.find('.more'));
            $footer.waypoint(opts);
        });
    }, opts);
});

any chance of a demonstration via jsfiddle?
good suggestion but worst js plugin waypoint.. wasted my lot of time.... answer below was much faster n quicker
Which answer below did you find to be the best?
You can refer to my answer for Lazy Loader implementation. stackoverflow.com/a/45846766/2702249
T
The Coprolal

If not all of your document scrolls, say, when you have a scrolling div within the document, then the above solutions won't work without adaptations. Here's how to check whether the div's scrollbar has hit the bottom:

$('#someScrollingDiv').on('scroll', function() {
    let div = $(this).get(0);
    if(div.scrollTop + div.clientHeight >= div.scrollHeight) {
        // do the lazy loading here
    }
});

Thanks bro! This really helped me :)
Best answer so far , thanks you're a life saver
C
Community

Here is an example:

On scrolling to the bottom, html elements are appeneded. This appending mechanism are only done twice, and then a button with powderblue color is appended at last.

Demo: Lazy Loader

Contents will load here!!!.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.

This is test data.
Next line.


@RohanAshik: I just checked. It's working. Try scrolling down till the end.
@Om Prakash Sao Its working fine here , but when i running this code in sublime then the event works when the scroll bar hit the top not the bottom,\
P
Prasanth K C

The accepted answer of this question has some issue with chrome when the window is zoomed in to a value >100%. Here is the code recommended by chrome developers as part of a bug i had raised on the same.

$(window).scroll(function() {
  if($(window).scrollTop() + $(window).height() >= $(document).height()){
     //Your code here
  }
});

For reference:

Related SO question

Chrome Bug


I like this answer as it has a nice smooth scroll and pause to it. Some other methods I used tend to load content too fast which makes for an awkward experience when trying to actually focus on the content and not the speed in which it loads.
This doesn't work on mobile devices
M
Moonis Abidi

Improving on @deepakssn answer. There is a possibility that you want the data to load a bit before we actually scroll to the bottom.

var scrollLoad = true;
$(window).scroll(function(){
 if (scrollLoad && ($(document).height() - $(window).height())-$(window).scrollTop()<=800){
    // fetch data when we are 800px above the document end
    scrollLoad = false;
   }
  });

[var scrollLoad] is used to block the call until one new data is appended.

Hope this helps.


T
Thanh Nguyen

I suggest using more Math.ceil for avoid error on some screen. Because on a few different screens it's not absolutely accurate I realized that when I console.log.

console.log($(window).scrollTop()); //5659.20123123890  

And

console.log$(document).height() - $(window).height()); // 5660

So I think we should edit your code to

$(window).scroll(function() {
    if(Math.ceil($(window).scrollTop()) 
       == Math.ceil(($(document).height() - $(window).height()))) {
           // ajax call get data from server and append to the div
    }
});

Or Allow load data from server before scroll until bottom.

if ($(window).scrollTop() >= ($(document).height() - $(window).height() - 200)) {
 // Load data
}

This solution is awesome to avoid the inaccuracies when users present different zoom levels on different browsers.
P
Pete - iCalculator

I spent some time trying to find a nice function to wrap a solution. Anyway, ended up with this which I feel is a better solutions when loading multiple content on a single page or across a site.

Function:

function ifViewLoadContent(elem, LoadContent)
    {
            var top_of_element = $(elem).offset().top;
            var bottom_of_element = $(elem).offset().top + $(elem).outerHeight();
            var bottom_of_screen = $(window).scrollTop() + window.innerHeight;
            var top_of_screen = $(window).scrollTop();

            if((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
            if(!$(elem).hasClass("ImLoaded"))   {
                $(elem).load(LoadContent).addClass("ImLoaded");
            }
            }
            else {
               return false;
            }
        }

You can then call the function using window on scroll (for example, you could also bind it to a click etc. as I also do, hence the function):

To use:

$(window).scroll(function (event) {
        ifViewLoadContent("#AjaxDivOne", "someFile/somecontent.html"); 

        ifViewLoadContent("#AjaxDivTwo", "someFile/somemorecontent.html"); 
    });

This approach should also work for scrolling divs etc. I hope it helps, in the question above you could use this approach to load your content in sections, maybe append and thereby dribble feed all that image data rather than bulk feed.

I used this approach to reduce the overhead on https://www.taxformcalculator.com. It died the trick, if you look at the site and inspect element etc. you can see impact on page load in Chrome (as an example).


I
Ihsan

You question specifically is about loading data when a div falls into view, and not when the user reaches the end of the page.

Here's the best answer to your question: https://stackoverflow.com/a/33979503/3024226