Thursday, February 12, 2009

Javascript ( JQuery ) Pagination

In every other WEB project you face you need pagination. I need to have this snippet at hand and so I have decided to post it here. I use JQuery and it is assumed I have a div#id=pagination nested into a div#id=content

function loadPagination(action, p, r, t){
var maxDirectPageLinks = 10;
var totalPages = t/r;
if(Math.floor(totalPages) != totalPages){
totalPages = Math.floor(totalPages) + 1;
}

$("#pagination").remove();
var start = 1;
var end = maxDirectPageLinks;

if(totalPages > 1){
if (maxDirectPageLinks < totalPages) {
if(p - maxDirectPageLinks/2 > 0 && p + maxDirectPageLinks/2 < totalPages) {
var start = p - maxDirectPageLinks/2 + 1;
var end = p + maxDirectPageLinks/2;
}else if(p - maxDirectPageLinks/2 < 0) {
var start = 1;
var end = maxDirectPageLinks;
}else if(p + maxDirectPageLinks/2 > totalPages) {
var start = totalPages - maxDirectPageLinks + 1;
var end = totalPages;
}
}else {
end = totalPages;
}
$("#content").append("
");
//$("#pagination").append("page " + p + " from " + totalPages + " pages for " + action + " (records per page/totalrecords=" + r + "/" + t);
if(p > 1){
$("#pagination").append("" + "Previous" + " ");
}
for(var i = start; i <= end; i++) {
if(i == p) {
$("#pagination").append(i + " ");
}else{
$("#pagination").append("" + i + " ");
}

}
if(p < totalPages){
$("#pagination").append("" + "Next" + " ");
}
$("#pagination").append("(" + totalPages + " total pages)")
}
}

1 comment:

kal said...

Hi,
Can you please provide a demo on this script - thank you

Followers