Javascript - Limit number of pages in pagination

Asked

Viewed 697 times

1

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’m not getting it. Could someone help me?

<< Start 1 2 3 4 5 End >> << Beginning 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"> &#171 </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"> &#187;</span>';
  return pagerHtml;
}

1 answer

1


I made some changes to make the script work. You can skip fillTable because it’s just to fill the table with numbers.

fillTable('table');
var pager = new Pager('table', 3, 'pager');
pager.init();
pager.showPage(1);

function Pager(tableName, itemsPerPage, pagerName) {
    this.tableName = tableName;
    this.itemsPerPage = itemsPerPage;
    this.pagerName = pagerName;
    this.maxPages = 5;
    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;
        }

        this.showPageNav(pageNumber);

        var oldPageAnchor = document.getElementById('pg'+this.currentPage);
        if (oldPageAnchor) {
            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(pageNumber) {
        if (! this.inited) {
            alert("not inited");
            return;
        }
        var element = document.getElementById(this.pagerName);
        var firstPage = parseInt(Math.max(pageNumber - this.maxPages / 2, 1));
        var lastPage = parseInt(firstPage + this.maxPages - 1);
        if (lastPage > this.pages) {
            lastPage = this.pages;
            firstPage = lastPage - this.maxPages;
            if (firstPage < 1) {
                firstPage = 1;
            }
        }
        var pager = this;
        element.innerHTML = '';
        element.appendChild(newSpan(' &#171 ', 'pg-ctrl', function () {
            pager.prev();
        }));
        for (var page = firstPage; page <= lastPage; page++) {
            element.appendChild(newSpan(page.toString(), 'pg-normal', changePage(pager, page)));
        }
        element.appendChild(newSpan(' &#187 ', 'pg-ctrl', function () {
            pager.next();
        }));
    }
}

function changePage (pager, page) {
    return function () {
        pager.showPage(page);
    };
}

function newSpan(text, className, onClick) {
    var span = document.createElement('span');
    span.id = 'pg' + text;
    span.innerHTML = text;
    span.className = className;
    span.onclick = onClick;
    return span;
}

function fillTable(id) {
    var table = document.getElementById(id);
    var html = '';
    for (var i = 0; i < 100; i++) {
        html += '<tr><td>' + (i + 1) + '</td></tr>';
    }
    table.innerHTML = html;
}
<table id="table"></table>
<div id="pager"></div>

  • Dude, by the time I get to the 5th element, my pagination doesn’t go forward and it doesn’t work with your new script anymore

  • In that part var pagerHtml = getPagerHtml(pagerName, 1, this.pages); you have to update the 1 with the variable you use to know which is the current page.

  • kakamg, I made the change but I haven’t succeeded yet :/

  • edited the asking, adding more information from the script

  • @Alexsandercaproni I think it is now working. I changed a little the way that is created the pagination spans.

  • Thank you even kakamg0! Saved my life

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.