I've been working for a while to make this code works perfect. so I did everything works good except for the paging buttons I'm afraid that I have to post the whole code here:
$(document).ready(function() {
var pager = new Pager('comments', 3);
pager.init();
pager.showPageNav('Pager', 'pageNavPosition');
pager.showPage(3);
function Pager(class_name, itemsPerPage) {
this.class_name = class_name;
this.itemsPerPage = itemsPerPage;
this.currentPage = 1;
this.pages = 0;
this.inited = false;
this.showRecords = function(from, to) {
var rows = $('.' + class_name);
// i starts from 1 to skip table header row
for (var i = 0; i < rows.length; i++) {
if (i < from || i > to)
rows[i].style.display = 'none';
else
rows[i].style.display = '';
}
}
this.showPage = function(pageNumber) {
if (! this.inited) {
alert("not inited");
return;
}
var oldPageAnchor = document.getElementById('pg'+this.currentPage);
oldPageAnchor.className = 'pg-normal';
this.currentPage = pageNumber;
var newPageAnchor = document.getElementById('pg'+this.currentPage);
newPageAnchor.className = 'pg-selected';
var from = (pageNumber - 1) * itemsPerPage;
var to = from + itemsPerPage - 1;
this.showRecords(from, to);
}
this.prev = function() {
if (this.currentPage > 1)
this.showPage(this.currentPage - 1);
}
this.next = function() {
if (this.currentPage < this.pages) {
this.showPage(this.currentPage + 1);
}
}
this.init = function() {
var rows = $('.' + class_name);
var records = (rows.length);
this.pages = Math.ceil(records / itemsPerPage);
this.inited = true;
}
this.showPageNav = function(pagerName, positionId) {
if (! this.inited) {
alert("not inited");
return;
}
and my problem is here:
var element = document.getElementById(positionId);
var pagerHtml = '<span onClick="' + pagerName + '.prev();" class="pg-normal"> « Prev </span> | ';
for (var page = 1; page <= this.pages; page++)
pagerHtml += '<span id="pg' + page + '" class="pg-normal" onClick="' + pagerName + '.showPage(' + page + ');">' + page + '</span> | ';
pagerHtml += '<span onClick="'+pagerName+'.next();" class="pg-normal"> Next »</span>';
element.innerHTML = pagerHtml;
}
}
});
if you wanna look at the demo please follow the link bellow http://jsfiddle.net/J3Qnx/11/
http://jsfiddle.net/justiceerolin/tes5N/
Creating the pager within $.ready does not create it globally, so it won't be able to reference Pager after it $.ready is complete (on clicks, etc)
Solution was to create a global pager instance, thisPager, and reference that instance instead.
The changes are the first four lines:
window.thisPager= new Pager('comments', 3);
thisPager.init();
thisPager.showPageNav('thisPager', 'pageNavPosition');
thisPager.showPage(3);