I have a script where I show all the pages of a table, for example,
< < 1 2 3 4 5 6 7 8 9 10 11 12 13 > >
However, I need to limit the display of the pages and I can not. Could someone help me?
< < Start 1 2 3 4 5 End > > < < Start 2 3 4 5 6 End > >
Follow the code already developed showing all pages:
function Pager(tableName, itemsPerPage) {
this.tableName = tableName;
this.itemsPerPage = itemsPerPage;
this.currentPage = 1;
this.pages = 0;
this.inited = false;
this.showRecords = function(from, to) {
var rows = document.getElementById(tableName).rows;
// i starts from 1 to skip table header row
for (var i = 1; 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 + 1;
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 = document.getElementById(tableName).rows;
var records = (rows.length - 1);
this.pages = Math.ceil(records / itemsPerPage);
this.inited = true;
}
this.showPageNav = function(pagerName, positionId) {
if (! this.inited) {
alert("not inited");
return;
}
var element = document.getElementById(positionId);
var pagerHtml = getPagerHtml(pagerName, this.currentPage, this.pages);
element.innerHTML = pagerHtml;
}
}
function getPagerHtml(pagerName, currentPage, pages, maxPages) {
maxPages = maxPages || 5; // default são 5 páginas
var firstPage = parseInt(Math.max(currentPage - maxPages / 2, 1)); // Obtém a primeira página a ser exibida adicionando algumas páginas antes da atual, ou a primeira caso não tenha
var lastPage = parseInt(firstPage + maxPages - 1); // Seleciona a última página a ser exibida
// Caso ultrapasse a quantidade de páginas refazemos a seleção das páginas a serem exibidas
if (lastPage > pages) {
lastPage = pages;
firstPage = lastPage - maxPages;
if (firstPage < 1) {
firstPage = 1;
}
}
var pagerHtml = '<span onclick="' + pagerName + '.prev();" class="pg-ctrl"> « </span>';
for (var page = firstPage; page <= lastPage; page++) {
pagerHtml += '<span id="pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '</span>';
}
pagerHtml += '<span onclick="'+pagerName+'.next();" class="pg-ctrl"> »</span>';
return pagerHtml;
}