Load More Posts onScroll (PHP/Ajax/Javascript/jQuery)
By William Thomas | Thursday, December 1, 2011
cetw
etwc
twce
wcet
cetw
etwc
twce
wcet
cetw
etwc
twce
wcet
cetw
etwc
twce
wcet
cetw
etwc
twce
wcet
cetw
etwc
twce
wcet
cetw
etwc
twce
wcet
cetw
etwc
twce
wcet
cetw
etwc
twce
wcet
cetw
etwc
twce
wcet
cetw
etwc
twce
wcet
cetw
etwc
twce
wcet
cetw
etwc
twce
wcet
cetw
etwc
twce
wcet
cetw
etwc
twce
wcet
cetw
etwc
twce
PHP:
index.php, file with the first page of content
<?php
mysql_connect(
"server",
"username",
"password");
$q = mysql_query(
"SELECT * FROM your_database.table LIMIT 0, 5");
//change the "5" if different from rows per page
while(
$r=mysql_fetch_array(
$q)){
$list .= $r[
'text']
.'<br>';
}
echo '<div id="list">'.$list.'</div>';
?>
load-more.php, where one page of content will be loaded at a time.
<?php
//PAGE NUMBER
if(
$_GET[
'page']){
$page = $_GET[
'page'];
}
else {
$page = 1;
}
//ROWS PER PAGE & OFFSET
$rrp = 5;
$offset = (
$page-1)
*$rrp;
//SHOWS A SPECIFIC PAGE OF CONTENT
$q = mysql_query(
"SELECT * FROM your_database.table LIMIT $offset, $rrp");
while(
$r=mysql_fetch_array(
$q)){
$list .= $r[
'text']
.'<br>';
}
//SHOWS IN THE #list ELEMENT WHILE GOING TO THE BOTTOM THE MAIN PAGE
echo $list;
?>
Ajax/jQuery
Place in the <head> of index.php
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
window.onscroll
= load_more;
var page
= 1;
//PAGE NUMBER ALREADY SHOWN
function load_more
(){
var doc_h
= document.body.scrollHeight;
//DOC HEIGHT
var win_h
= document.body.clientHeight;
//WINDOW HEIGHT
var d
= doc_h
-win_h;
//DIFFERENCE OF DOC & WINDOW HEIGHT
var yOffset
= window.pageYOffset;
//WINDOW SCROLLBAR Y OFFSET
//IF SCROLLBAR OFFSET EQUALS DIFFERENCE
if(yOffset
==d){
page
++;
//LOAD THE NEXT PAGE ONE AT A TIME
$.get(
"load-more.php?page="+page, function(data){
$(
"#list").append(data);
//WILL SHOW IN THIS ELEMENT IN 'index.php';
});
}
}
</script>