Add content dynamically as you reach end of page with AJAX

Thu, 27th Dec, '07

You have a search page and as the results end you show a navigation bar with links to the other pages of the search. So boring. Seriously. This is the Web, and I am still turning pages.

And I think I am Pied Piper who will save you from this hell. The uber-cool solution is, detect as soon as a user is about to reach the end of the page and get new content[the second page of the search], just in time. Setting out, we need:

The height of the current document. So to this end, we will place a div with a decided upon ID at the end of the page. And all the content in the body will be loaded in another div just above this last div. We are detecting the document height by detecting where this ending div is located, pixel-wise, with this:

pageend = document.getElementById(‘laststop’).offsetTop;

So clearly, the ID of the last div is ‘laststop’. Next we need the screen resolution of the client window to find out how much of the document is visible right now. We do:

winheight = (typeof window.innerHeight != ‘undefined’ ? window.innerHeight : document.body.offsetHeight);

Now having this much, we need to detect when does the user scroll the page to the bottom. The following lines will give exactly how many pixels from the top have you scrolled to. Note that, this is the ‘height’ from the top of the document to the top of the visible area. The real end of the document is obtained by adding this ‘height’ and the window height retrieved earlier.

if(navigator.appName == “Microsoft Internet Explorer”)

But these lines need to be run every few seconds to check as soon as as the user reaches the end of the current page. So we will do a setInterval() in the onload event of the body to do so. And keep the interval time to something a little over 2 seconds and nothing less than that, you of course don’t want your user’s browser to hang on them. It is annoying.

Said and done, this is what you end up with, demofile.php, annotated with explanatory comments:

<title>Page End Reached Detection Demo</title>
<script type=”text/javascript”>
var oRequest;
var pageend, winheight;
var howoften = 2000;
// this value implies that function howlow() will keep checking every
// 2000 milliseconds(2 seconds) to find out how low is the user on the page

var bufferHeight = 300;
// adjust bufferHeight, to take action as soon as the user is within these
// many pixels of the end of the page, so a larger buffer makes sure the user doesn’t
// see the dynamic page content loading. In this example, the script will fetch content
// as soon as you are within 200 pixels of the end of the page

// ooooo, ajax. ooooooo …
oRequest = new XMLHttpRequest();
else if(window.ActiveXObject)
oRequest = new ActiveXObject(“Microsoft.XMLHTTP”);

function sendAReq()
// a generic function to send away any data to the server
// specifically ‘morecontent.php’ in this case, to get more content from the server
// all content fetched will be handled by showcontent()
{“POST”, “morecontent.php”, true);
oRequest.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”);
oRequest.onreadystatechange = showcontent;

function showcontent()
if(oRequest.readyState == 4)
// now all the data that comes adds to the end of the page, specifically
// to the container div referenced with the ID ‘bodycontent’
if(oRequest.status == 200)
document.getElementById(‘bodycontent’).innerHTML = document.getElementById(‘bodycontent’).innerHTML + oRequest.responseText;
alert(‘No Response from Server. Try Again Later.’);

function calcParams()
// calculate the end coordinates of the page and the visibile height of a page
// at any time on the client’s desktop
pageend = document.getElementById(‘laststop’).offsetTop;
winheight = (typeof window.innerHeight != ‘undefined’ ? window.innerHeight : document.body.offsetHeight);

function isitend(curpos)
if((curpos + winheight + bufferHeight) > pageend)
alert(‘you are reaching the end of the page;’);
alert(‘keep going’);

function howlow()
if(navigator.appName == “Microsoft Internet Explorer”)

<body onload=”javascript:setInterval(‘howlow()’,howoften);”>
<div id=’bodycontent’>
for($index=0; $index<200; $index++)
echo ‘Line:’.$index.'<br>’;
<div id=’laststop’/>

Oh and yeah, this sends a request using the XMLHttp object so we need another php file at the server to catch the request and send in additional content. This additional content will be appended to the div with ID ‘bodycontent’. So here is morecontent.php

for($index = 0; $index < 100; $index++)
echo ‘We Are New Lines:’.$index.'<br>’;

That’s about it. Please do throw in your experiences with this in the comments section below and I will surely respond. I am jobless. 🙂


7 Responses to “Add content dynamically as you reach end of page with AJAX”

  1. asianblue Says:

    how to do the jsp version instead of php?

  2. krahulg Says:

    Hi asianblue,
    well, there is not much php in this example, except for the file “morecontent.php”. You can replace that with your own jsp file and while doing a AJAX call from “sendAReq()” the request will be sent to your JSP file instead.
    And the little bit of php in demofile.php is just to generate some content to increase the length of the page. But then this is a example.
    I hope that helps.

  3. Asianblue Says:


    i am looking at how to load external html within the page instead of writing dummy text.

  4. krahulg Says:

    if all you mean by external html is html generated by your script, just send html as an AJAX response to the client browser and it will be added. try it out and let me know.

  5. yellen Says:

    suppose we have multiple div elements in the page, say a whole left-pane, a middle-pane and a right-pane. And, say, the search result is to be displayed in the middle-pane( middle-div), however we are also getting other feeds in the other panes as well. what becomes of the page when we scroll down? A bit foolish question here :p. Just a rookie.

    And will this have the same effect in other browsers? All these cross-browser codes turns me head!!

  6. yellen Says:

    sorry about the earlier comment. Got the picture now. 🙂
    But still a little doubt on performance in different browsers!!

  7. krahulg Says:

    this works in IE6.0+ and FF2.0+, have to check in Safari though.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: