home

Infinite scroll : Loading content while scrolling, using Java and JQuery

July 13, 2010 · 21 comments

Have you seen the infinite scrolling of content in some web pages? For example, in DZone.com when you scroll the page to the bottom, new links will be loaded automatically and it’ll give you the illusion that the page scrolls infinitely. Another good example is that Bing’s Image Search.

The technique is not hard to implement. With the use of a single servlet and JSP, we can implement a basic functionality with infinite scroll. Before dive into code details, have a look at this demo to get a feel of it: Infinite Scroll Demo

To implement this, we need a servlet which will serve the dynamic content and a JSP file which will have the UI and act as a client to receive the content. Below are the code for these two files. I’m leaving other common stuffs (like web.xml entry etc) to you.

Code for Servlet:

package com.vraa.demo;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class InfinitContentServlet extends HttpServlet {
    private static Integer counter = 1;

    protected void processRequest(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        try {
            String resp = "";
            for (int i = 1; i <= 10; i++) {
                resp += "<p><span>"
                        + counter++
                        + "</span> This is the dynamic content served freshly from server</p>";
            }
            out.write(resp);
        } finally {
            out.close();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }
}

Code for JSP file:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Load content while scrolling - Infinite Scroll with Java and JQuery</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
        <style type="text/css">
            body{
                font-family:Arial;
                font-size:.93em;
            }
            #content-box{
                background-color:#FAFAFA;
                border:2px solid #888;
                height:300px;
                overflow:scroll;
                padding:4px;
                width:500px;
            }
            #content-box p{
                border:1px solid #EEE;
                background-color:#F0F0F0;
                padding:3px;
            }
            #content-box p span{
                color:#00F;
                display:block;
                font:bold 21px Arial;
                float:left;
                margin-right:10px;
            }
        </style>
        <script type="text/javascript">
            $(document).ready(function(){
                $contentLoadTriggered = false;
                $("#content-box").scroll(function(){
                    if($("#content-box").scrollTop() >= ($("#content-wrapper").height() - $("#content-box").height()) && $contentLoadTriggered == false)
                    {
                        $contentLoadTriggered = true;
                        $.get("infinitContentServlet", function(data){
                            $("#content-wrapper").append(data);
                            $contentLoadTriggered = false;
                        });
                    }

                });
            });
        </script>
    </head>
    <body>
        <h1>Demo page: Infinite Scroll with Java and JQuery</h1>
        <p>This page is a demo for loading new content while scrolling.</p>
        <p style="margin:20px 0;background-color:#EFEFEF;border:1px solid #EEE;padding:3px;">
        	Credits: Veera Sundar | <a href="http://veerasundar.com">veerasundar.com</a> | <a href="http://twitter.com/vraa">@vraa</a>
        </p>
        <div id="content-box">
            <div id="content-wrapper">
                <p><span>1</span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ornare facilisis mollis. Etiam non sem massa, a gravida nunc. Mauris lectus augue, posuere at viverra sed, dignissim sed libero. </p>
                <p><span>2</span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ornare facilisis mollis. Etiam non sem massa, a gravida nunc. Mauris lectus augue, posuere at viverra sed, dignissim sed libero. </p>
                <p><span>3</span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ornare facilisis mollis. Etiam non sem massa, a gravida nunc. Mauris lectus augue, posuere at viverra sed, dignissim sed libero. </p>
                <p><span>4</span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ornare facilisis mollis. Etiam non sem massa, a gravida nunc. Mauris lectus augue, posuere at viverra sed, dignissim sed libero. </p>
                <p><span>5</span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ornare facilisis mollis. Etiam non sem massa, a gravida nunc. Mauris lectus augue, posuere at viverra sed, dignissim sed libero. </p>
            </div>
        </div>
    </body>
</html>

How it works?

The secret behind this is the scrolltop property. By checking this value we can determine whether the scrollbar has reached near to the bottom or not. If it reached, send an AJAX request to server to get more content and append it to the page. Look at the following two lines which does this:

 $contentLoadTriggered = false;
 $("#content-box").scroll(function(){
     if($("#content-box").scrollTop() >= ($("#content-wrapper").height() - $("#content-box").height()) && $contentLoadTriggered == false)
     {
         $contentLoadTriggered = true;
         $.get("infinitContentServlet", function(data){
             $("#content-wrapper").append(data);
             $contentLoadTriggered = false;
         });
     }

 });

Related Posts

{ 19 comments… read them below or add one }

tee are July 14, 2010 at 9:50 PM

thanks for sharing.. i’ll try it at once :D

Reply

yulianti July 20, 2010 at 9:58 PM

i’m trying for Java.. this very helpfull

Reply

syaramal July 30, 2010 at 2:06 AM

Hi,

Thanks for the article. I tried it and works for me when page is loaded completely.
When a part of the page is loaded, the above script is not working. Probably reason being due to the on document.ready function.

Can anyone help me here to call the script when a part of page is refreshed?

I appreciate your help.

Thanks

Reply

Veera July 30, 2010 at 9:44 AM

Instead of writing code inside document ready event, you can use $(“yourelementid”).ready() method.

Reply

syaramal July 30, 2010 at 11:04 PM

Thanks for the quick reply.
I tried it too before including the code in just $(“myelementid”).ready(). It didn’t work for me.

I appreciate your help.

Thanks

Reply

Veera July 30, 2010 at 11:38 PM

if possible can you share the code which you are trying to do?

Reply

syaramal July 31, 2010 at 12:05 AM

Thanks a lot for the quick reply!

Below is sample code. We were using ajax tags for refreshing a part of the page.

Jquery code

$contentLoadTriggered = false;

$(“#content-box”).ready(function(){
$(“#content-box”).scroll(function(){
if($(“#content-box”).scrollTop() >= ($(“#content-wrapper”).height() – $(“#content-box”).height()) && $contentLoadTriggered == false)
{
$contentLoadTriggered = true;
$.get(“addContent.htm”,{pageOffset : “next”}, function(data){
$(“#content-wrapper”).append(data);
$contentLoadTriggered = false;
});
}

});

});

content-box and content-wrapper are my div’s wrapped between my list (table) which is list of applications displayed. The script works fine when the complete page is loaded. We have a mechanism to select some filters against the master list, we refreshing the part of page (content-box and content-wrapper div’s) based on the selected filters. Now I want the load on scroll script work for the updated list too.

Hope I explained it clearly.

I really appreciate your help.

Thanks,

Reply

Hemal July 31, 2010 at 1:09 PM

Hey Veera, is this functionality achievable without JSP?

Reply

Tom Namla August 12, 2010 at 4:44 PM

For me it did’nt work ( WebSphere 7 ), there was a simple typo:
In the code it calls the servlet
$.get(“infinitContentServlet”, function(data){
but it should be
$.get(“InfinitContentServlet”, function(data){

Reply

nikhil December 1, 2010 at 1:27 PM

Hi Veera ,
I need your help in implementing infinite scrolling. I have scenario which load content dynamically depending on some fields.so is there any way to pass parameter to servlet from jquery function..

your reply will be highly appreciated

Thanks
Nikhil

Reply

Veera December 1, 2010 at 2:16 PM

It is possible to pass parameter to servlet from a JQuery function. There are two ways to do the same:

1) Having your parameters as <input type=’hidden’ name=’yourName’ value=’yourValue’ />
2) Before sending an AJAX request to Servlet, manually including your parameters to the request. For example, like this: $.post(“yourServletPath”, { yourVaribale: “value”, otherVariable: “value2″ } ); [more examples]

Reply

nikhil December 1, 2010 at 2:57 PM

Sorry to disturb you again ..
Let me explain my scenario first i have one page consist of different panel and want load panel once it get focused .So is there any way to load whole panel by passing id and displaying the content of panel according to panel id during scrolling.

your hep will be highly appreciated

Thanks
Nikhil

Reply

Veera December 3, 2010 at 12:17 PM

Hi Nikhil.

it is possible.. please contact me in email so that I can explain further.

Reply

Martin May 24, 2011 at 6:03 PM

Hi Veera,

i searched google for “infinite scroll with thesis”, because i cant get the worpress (i got 3.1.2) plugin infinite scroll to work, and i suspect it has something to do with thesis. But i didnt find any clues. I would be super-happy if you could help, it seems like it would be easy for you too.

i have the following settings for the plugin:
Content CSS Selector: #content_box
Post CSS Selector: #content div.post
Navigation Links CSS Selector: div.prev_next
Previous posts CSS Selector: div.previous a:first

Reply

Martin May 24, 2011 at 10:42 PM

ok got it.
please delete both comments
made a mistake with the Selectors

Reply

Richard Hance July 3, 2011 at 4:14 AM

Scrolling internet web results is available on Norele.com. If the data base has the information, It is easier and faster than paging.

Reply

karthik August 12, 2011 at 5:40 PM

Can this is possible when scrolling browser scroll bar?

Reply

Veera August 15, 2011 at 3:16 AM

Yes. it is very well possible.

Reply

Bala H January 27, 2012 at 5:14 PM

Add below for IE9 or firefox9
#content-wrapper {
height:auto;
overflow:hidden;
}

Reply

Leave a Comment

{ 2 trackbacks }

Previous post:

Next post: