Javascript Scroll to load in Div



2.11 K Views | Rishi Kashyap | 1
Rishi Kashyap
8.66 K
X

Javascript Scroll to load in Div


0

Loading data in a div element while scrolling down is more user friendly than giving them next/back page links. In Javascript Scroll div to bottom we learned basics of how div element and scroll bar can be accessed using Javascript. Extending the same we will try to load data in div while scrolling using AJAX.

The required html<div id="the_div1" class="divbox" onscroll="scrolldiv();">
<div class="box">This is Box Number 1</div>
<div class="box">This is Box Number 2</div>
<div class="box">This is Box Number 3</div>
<div class="box">This is Box Number 4</div>
<div class="box">This is Box Number 5</div>
</div>
<div id="btm"></div>
The div with id "the_div1" has "onscroll" event added to trigger the required javascript. "btm" div is there to show the changes to you while scrolling. The required javascript with comments
<script type="text/javascript">
var num=1;
//Reduce typing document.getElementById again and again
function $(x){return document.getElementById(x);}
//Measure and display the scroll bar position also check if we have reached end of scroll
//onscroll event binded to div element
function scrolldiv()
{
//Remaining pixel to bottom
var remain =$("the_div1").scrollHeight-$("the_div1").scrollTop;
//Show remaining in btm div for understanding
$("btm").innerHTML="<center class=\'alert\'>"+remain+"</center>";
//If remaining less than 600 px, load in div by AJAX while scrolling
//Also limit to max 5 AjAX calls
if(remain < 600 && num < 5){
//Add a new div using DHTML
$("the_div1").innerHTML +="<div id=\'new"+num+"\'></div>";
//Make ajax call and oad the data in the new div created above
callAHAH("/e/aj_javascript-scroll-div.php","p="+num,"new"+num,"Getting more data...");
//Increase the number
num++;}
//If already at bottom then indicate that
if(remain==$("the_div1").clientHeight){$("btm").innerHTML=
"<center class=\'alert\'>5 AJAX Called made and now you have reached Bottom</center>";}
}
</script>';
CSS can be anything, mine to decorate the Div is .divbox{border:5px solid #000;padding:4px;margin:3px;height:150px;overflow:auto;width:90%;}
.alert{color:red;font-weight:bold;background:#F2F2F2;border:1px solid #000;padding:1px;margin:1px;}
.highlight{background:#C4ECFF;padding:2px;margin:1px;border:1px solid #000;}
.box{height:100px;border:2px solid #000;margin:2px;padding:2px;font-weight:bold;text-align:center;}

I am using very simple AJAX, ofcourse the AJAX returned data on your website will be more complex as per your need to load in div while scrolling.Javascript Scroll to load in Div

Rishi Kashyap | | EDIT | REPLY


tags  JAVASCRIPT JAVASCRIPT AJAX

SUBSCRIBE TO RISHI'S BLOGS