Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement an endless/infinite scroll within a DIV in Javascript/jQuery [duplicate]

I realize there are several questions here that address the issue of endless scrolling. However most of them are using plugins.

I'd like to know how to implement endless scrolling that would work with my existing paging functionality. Currently I have a "load more" button, when clicked on, will fetch the next 10 items, and append to the list. Instead of doing this when the "load more" button is clicked, I'd like it to happen when the scroll position comes to the bottom. Also, this list is not on the main page, it's within a DIV. Storing the page number in a hidden field with id 'pageNum'.

$.ajax({
        type: "GET",
        url: "/GetItems",
        data: { 'pageNum': $('#pageNum').val() },
        dataType: "json",
        success: function (response) {
                $('#MyDiv ul').append(response.Html);
                $('#pageNum').val(response.PageNum);
            }
        }
});

#MyDiv
{
    border:solid 1px #ccc; 
    width:250px;
    height:500px;
    overflow-y: scroll;
}

<div id="MyDiv">
  <ul>
    <li>...</li>
    ...
  </ul>
</div>
like image 516
Prabhu Avatar asked Mar 03 '13 01:03

Prabhu


People also ask

What is infinite scrolling in jquery?

Infinite Scroll is a JavaScript plugin that automatically adds the next page, saving users from a full page load.

Does JavaScript have infinite scroll?

Infinite scrolling is a feature that allows you to load some pics on a website and then load more once the user reaches the end of the webpage (like we see on Pinterest). We will start off by creating three files, index. html , style. css , and app.

Why you shouldn't use infinite scroll?

If you're using infinite scrolling on a long page, you're constantly loading more and more content into memory. This will have a negative impact on page performance, since the browser has much more work to do in order to render the page.


1 Answers

The simplest way, is to check if you've reached the bottom and to trigger then a click-event on your "load more"-button.

$(window).on('scroll', function(){
    if( $(window).scrollTop() > $(document).height() - $(window).height() ) {
        $("#load-more").click();
    }
}).scroll();

The script above is just an example, don't use it in your production environment.

update

...and the better way is to call the function instead of trigger an event which calls the function.

update2

...and the best way: let the user decide what is to do if he do (in this case he scrolls down to reach the end of your page, not to reach the next page) ;)

like image 72
yckart Avatar answered Oct 09 '22 17:10

yckart