6

I want to load the content in div.I got many jquery scoll plugins but all are they for whole page load.I want to load content in existing div when scroll reaches at bottom of div.Can anyone help me ?

ZOE RULE
  • 99
  • 1
  • 2
  • 11

3 Answers3

7

You can do something like this using JQuery and Ajax:

var loading = false;//to prevent duplicate

function loadNewContent(){       
    $.ajax({
        type:'GET',
        url: url_to_new_content    
        success:function(data){
            if(data != ""){
                loading = false;
                $("#div-to-update").html(data);
            }
        }
    });
}

//scroll DIV's Bottom 
$('#div-to-update').on('scroll', function() {
    if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
        if(!loading){
            loading = true;
            loadNewContent();//call function to load content when scroll reachs DIV bottom                
        }   
    }
})


//scroll to PAGE's bottom
var winTop = $(window).scrollTop();
var docHeight = $(document).height();
var winHeight = $(window).height();
if  ((winTop / (docHeight - winHeight)) > 0.95) {       
    if(!loading){
        loading = true;
        loadNewContent();//call function to load content when scroll reachs PAGE bottom                
    }       
}

FIDDLE

Merlin
  • 4,907
  • 2
  • 33
  • 51
3

You can do something like this using JQuery and this lazyload plugin.

Your div:

<div data-src="transparent.png" url="http://stackoverflow.com"></div>

Use beforeLoad callback:

jQuery(function($) {
    $("div[url]").lazy({
        beforeLoad: function (element) {
            element.load(element.attr("url"));
        }
    });
});
eisbehr
  • 12,243
  • 7
  • 38
  • 63
1

I know it's an old topic, but just to be complete: As said before, you could use jQuery.Lazy for this. But I would not do it the here shown way. :) There is already a plugin for loading <div> content via AJAX too.

Add the Plugin to your page: (you will need jQuery or Zepto as well)

<script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazy/1.7.1/jquery.lazy.min.js"></script>
<script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazy/1.7.1/plugins/jquery.lazy.ajax.min.js"></script>

Prepare your div's: (note the data-loader and data-src attributes)

<div data-loader="ajax" data-src="ajax.html"></div>

And start using Lazy:

$(function() {
    $("div[data-src]").Lazy();
});

That's it! The content given in data-src will be loaded whenever the user reaches the <div> by scrolling. More inormations here.

eisbehr
  • 12,243
  • 7
  • 38
  • 63
  • **Type: Offtop**. Excuse me, eisbehr, can you read when you will have a free time [**this question**](https://stackoverflow.com/q/63753845/5951529) — how is it possible to do lazy loading for comments on the site via your jQuery.Lazy plugin? Thanks. – Саша Черных Sep 11 '20 at 15:55