ZOE RULE
ZOE RULE

Reputation: 97

jquery lazy load content in div

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 ?

Upvotes: 6

Views: 39164

Answers (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"));
        }
    });
});

Upvotes: 3

eisbehr
eisbehr

Reputation: 12452

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.

Upvotes: 1

Merlin
Merlin

Reputation: 4917

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

Upvotes: 7

Related Questions