Tuesday, July 3, 2012

Javascript : On scroll fill data at the end of the page

Other day while browsing facebook, i saw when we scroll to the end of the home page it fills more data without refreshing the whole page. Again when u reach to the end of the page it fetches more data and this continues. I didn't bother to check its upper limit, may be at some point of time it will go out of memory of the browser.

So lets see how this functionality can be achieved. Below javascript variables can be used to detect when user have reached to the end of the body.

  • document.body.scrollTop - scroll bar position
  • document.body.scrollHeight - height of the scroll bar
  • document.body.clientHeight - total height of the body

so if (scrollHeight - scrollTop) is equal to clientHeight you have reached to the end of the body. And obviously you can use various APIs like AJAX, DWR, Ext JS etc to load data without refreshing the whole page.

Below is the standalone tested HTML code, directly you can test this example no need to have any server. Please see the self explanatory html code.


<HTML>

<HEAD>
<TITLE>Scroll Example</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
divCount = 1;
function onScrollDiv()
{
if((document.body.scrollHeight - document.body.scrollTop) == document.body.clientHeight)
{
onLoadData();
}

return false;
}

function onLoadData()
{
previousCount = divCount;
divCount++;

//Get data using AJAX, DWR, Ext JS etc
htmlData = "<table width='50%' border='1'><tr><td height='200px' align='center'>"+new Date()+"</td></tr></table>";

document.getElementById("div"+previousCount).innerHTML = htmlData;

var newDiv = document.createElement("div");
newDiv.innerHTML = "<div id='div"+divCount+"'>Loading...</div>"
var previousDiv = document.getElementById("div"+previousCount);

insertAfter(newDiv,previousDiv.parentNode);
return false;
}

function insertAfter(new_node, existing_node) {

if (existing_node.nextSibling) {
existing_node.parentNode.insertBefore(new_node, existing_node.nextSibling);
} else {
existing_node.parentNode.appendChild(new_node);
}
}

//-->
</SCRIPT>
</HEAD>
<BODY onload="onLoadData();" onscroll="onScrollDiv();">
<center>
Simple Javascript example which fills data when you scroll at the end of the file same like Facebook
<br />
Resize the window so that scroll bar appears on the right hand side then you can test it.

<div>
<div id="div1"></div>
</div>

</center>
</BODY>
</HTML>