3
\$\begingroup\$

I have made this Pagination Class in JS which takes the following configurations :-

  • Total records
  • Records per page
  • Visible pages

The idea is simple that any instance created using this Pagination class should be easy to use and separate the view logic from the pagination logic. I have also added few validations as per the configurations passed as of now.

Below is the code :-

// Records to paginate on 
const records = [
    ...Array(346)
      .fill("")
      .map((val, index) => `Name-${val - index}`)
  ];


// Paginator Class
class Paginator {
  constructor(totalRecords, recordsPerPage = 1, visiblePages = 1) {
    this.recordsPerPage = recordsPerPage;
    this.totalRecords = totalRecords;
    this.noOfPages = Math.ceil(this.totalRecords / this.recordsPerPage);
    this.visiblePages = visiblePages;
    this.activePage = 1;
    this.visiblePagesEndRange = visiblePages;
    // below validations can be improved and really not necessary for bare minimum pagination but 🤷‍♂️
    this.validate();
  }

  validate() {
    if (this.recordsPerPage <= 0) {
      this.recordsPerPage = 1;
    }
    if (this.visiblePages <= 0) {
      this.visiblePages = 1;
    }
    if(this.totalRecords<=0){
      this.totalRecords = 1;
    }
    if (this.noOfPages <= 0) {
      this.noOfPages = Math.ceil(this.totalRecords / this.recordsPerPage);
    }
    if (this.visiblePagesEndRange <= 0) {
      this.visiblePagesEndRange = this.visiblePages;
    }
    if (this.visiblePages > this.noOfPages) {
      this.visiblePages = this.noOfPages;
      this.visiblePagesEndRange = this.visiblePages;
    }
    if (this.recordsPerPage > this.totalRecords) {
      this.recordsPerPage = this.totalRecords;
    }
  }

  gotoNextPage() {
    if (this.activePage < this.noOfPages) {
      this.activePage += 1;

      if (this.activePage > this.visiblePagesEndRange) {
        this.visiblePagesEndRange += this.visiblePages;
        this.visiblePagesEndRange = Math.min(this.visiblePagesEndRange, this.noOfPages);
      }
    }
  }

  gotoPrevPage() {
    if (this.activePage > 1) {
      this.activePage -= 1;
      if (this.activePage % this.visiblePages === 0) {
        this.visiblePagesEndRange = this.activePage;
      }
    }
  }

  gotoFirstPage() {
    this.activePage = 1;
    this.visiblePagesEndRange = this.visiblePages;
  }

  gotoLastPage() {
    this.activePage = this.noOfPages;
    this.visiblePagesEndRange = this.noOfPages;
  }

  gotoPage(page) {
    this.activePage = page;
  }

  getVisiblePagesRange() {
    let beginningVisiblePage;
    let endingVisiblePage;
    //  When the visiblepagesendrange % visiblepages is not zero (which means that all the pages cannot be fit in the visible pages range) and if our ending page range is equal to total no pages then the beginning would be equivalent to visble page range - ((visible page range mod visiblepage range) - 1) i.e the leftover pages until the end. 
    if (this.visiblePagesEndRange % this.visiblePages !== 0 && this.visiblePagesEndRange === this.noOfPages) {
      beginningVisiblePage =
this.visiblePagesEndRange - ((this.visiblePagesEndRange % this.visiblePages) - 1);
    }
    // else we are always in a place where, current visible page end range - visible page range + 1 will return us the correct beginning position for the page range.
    else {
      beginningVisiblePage = this.visiblePagesEndRange - this.visiblePages + 1;
    }
    //Also endingActivePage would be simply equal visiblePagesEndRange.
    endingVisiblePage = this.visiblePagesEndRange;
    return {
      beginningVisiblePage,
      endingVisiblePage
    };
  }

  getActivePageIndices() {
    // the beginning page index will be current active page multiplied by no of records.
    let beginningPageIndex = (this.activePage - 1) * this.recordsPerPage;
    // the ending page index will be minimum of total records and (beginning + records allowed per page);
    let endingPageIndex = Math.min(
      beginningPageIndex + this.recordsPerPage,
      this.totalRecords
    );
    return { beginningPageIndex, endingPageIndex };
  }
}

// All the render and using Paginator class logic comes here
(function () {
  function nextPage() {
    paginator.gotoNextPage();
    render();
  }

  function prevPage() {
    paginator.gotoPrevPage();
    render();
  }

  function lastPage() {
    paginator.gotoLastPage();
    render();
  }

  function firstPage() {
    paginator.gotoFirstPage();
    render();
  }

  // Delegating event to the parent ul.
  function gotoPage(event) {
    if (event.target.nodeName === "BUTTON") {
      const page = parseInt(event.target.dataset.item);
      paginator.gotoPage(page);
      render();
    }
  }

  const paginationPages = document.querySelector(".pagination__pages");

  paginationPages.addEventListener("click", gotoPage);

  /* paginator object 
  list which is of length 346
  recordsPerPage = 6
  visiblePages = 6  
  */
  const paginator = new Paginator(records.length,6, 6);

  // Method to render the pagination buttons;
  function renderPages() {
    const paginationPages = document.querySelector(".pagination__pages");
    let html = "";
    let {
      beginningVisiblePage,
      endingVisiblePage
    } = paginator.getVisiblePagesRange();
    for (let page = beginningVisiblePage; page <= endingVisiblePage; page++) {
      const pageClass =
        paginator.activePage === page
          ? "pagination__page-btn--active"
          : "pagination__page-btn";
      html += `<li class='pagination__page'>
   <button data-item=${page} class=${pageClass}>${page}</button>
     </li>`;
    }
    paginationPages.innerHTML = html;
  }

  // Method to render the list items
  function renderList() {
    const list = document.querySelector(".list");
    const {
      beginningPageIndex,
      endingPageIndex
    } = paginator.getActivePageIndices();
    let html = "";
    for (let index = beginningPageIndex; index < endingPageIndex; index++) {
      html += `<li class='list__item'>${records[index]}</li>`;
    }
    list.innerHTML = html;
  }

  // Main render function
  function render() {
    renderPages();
    renderList();
  }

  render();

  this.firstPage = firstPage;
  this.lastPage = lastPage;
  this.nextPage = nextPage;
  this.prevPage = prevPage;
  this.gotoPage = gotoPage;
})();
.pagination__pages {
  display: inline-flex;
  list-style-type: none;
  padding: 0;
}

.pagination__page-btn{
    border:1px solid black;
}

.pagination__navigate-btn {
  border:1px solid black;
}

.pagination__page-btn--active {
  border:1px solid black;
  background: #a3a3ff;
}

.list {
  list-style-type: none;
  padding: 0;
}

.app-container{
  display:flex;
  flex-direction:column;
  align-items:center;
}
<section class='app-container'>
  <ul class='list'>

  </ul>
  <div class='pagination__wrapper'>
    <section class='pagination__items'>
      <button class='pagination__navigate-btn' onclick='firstPage()'>First</button>
      <button class='pagination__navigate-btn' onclick='prevPage()'>Prev</button>
      <ul class='pagination__pages'>

      </ul>
      <button class='pagination__navigate-btn' onclick='nextPage()'>Next</button>
      <button class='pagination__navigate-btn' onclick='lastPage()'>Last</button>
    </section>
  </div>
</section>

I am interested in knowing the pitfalls of it and any scope of improvement for the same.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$
  1. I think Paginator need only one change page
  2. in most cases, an Ajax request is required and we have to take care of this callback (render - is callback )
  3. we have to create methods for change limit (changeMax)
  4. we have to create methods for change locale (changeLocale)
  5. external code should not affect the paginator (nextPage, prev ... inside class Paginator) use callbacks

Example

const records = [
    ...Array(346)
        .fill("")
        .map((val, index) => `Name-${val - index}`)
];

class Paginator {

    constructor(max, visible, id, callback) {
       this.max = max;
       this.visible = Number(visible);
        this.id = id;
        this.offset = 0;
        this.pageEvent = callback;
        this.btnFirst = 'First';
        this.btnLast = 'Last';
        this.btnNext = 'Next';
        this.btnPrev = 'Prev';
    }


    init(total, max, current = 1) {
        this.total = Number(total);
        this.max = Number(max);
        this.pages = Math.ceil(this.total / this.max);
        this.goToPage(current);

        return this;
    }


    changeLocale(locale) {

        this.btnFirst = locale.first;
        this.btnLast = locale.last;
        this.btnNext = locale.next;
        this.btnPrev = locale.prev;
        this.render();
    }

    changeMax(max) {

        this.init(this.total, max, this.visible, this.id, this.pageEvent);
    }

    goToPage(page) {
        this.current = page;
        this.offset = Number((page - 1) * this.max);
        this.limit = Number(this.offset + this.max < this.total ? this.max : this.total - this.offset);
        this.render();
        this.pageEvent(this.current,  this.offset, this.limit);
    }

    render() {
        const id = this.id;
        let elem = document.getElementById(id);
        elem.innerHTML = '';
        if (this.pages < 2) return;
        if (this.pages <= this.visible) {
            for (let i = 1; i <= this.pages; i++) {
                this.addElem(elem, i, i);
            }
        } else {
            this.addElem(elem, this.btnFirst, 1);

            if(this.current <= this.visible) {
                for (let i = 1; i <= this.visible; i++) {
                    this.addElem(elem, i, i);
                }
                let next = (this.current + this.visible) - ((this.current + this.visible - 1)%this.visible);
                next = next > this.pages ? this.pages : next;
                this.addElem(elem, '...');
                this.addElem(elem, this.btnNext, next);
            }

            else if(this.current > this.visible && this.current < (this.pages - 1)) {
                let prev = (this.current - this.visible) - ((this.current + this.visible - 1)%this.visible);
                prev = prev < 1 ? 1 : prev;
                let next = (this.current + this.visible) - ((this.current + this.visible - 1)%this.visible);
                next = next > this.pages ? this.pages : next;
                this.addElem(elem, this.btnPrev, prev);
                this.addElem(elem, '...');
                for (let i = this.current; i < this.current + this.visible; i++) {
                    this.addElem(elem, i, i);
                }
                this.addElem(elem, '...');
                this.addElem(elem, this.btnNext, next);

            }

            else {
                this.addElem(elem, this.btnPrev, this.current - 1);
                this.addElem(elem, '...');
                for (let i = this.pages - this.visible; i <= this.pages; i++) {
                    this.addElem(elem, i, i);
                }

            }

            this.addElem(elem, this.btnLast, this.pages);
        }
    }


    addElem(elem, name, page = null) {
        let el = document.createElement("div");
        const that = this;
        el.innerHTML =
            `<p class="page ${this.current == page ? 'active': ''}" >${name}</p>`;
        elem.appendChild(el);
        if(page) {
            el.addEventListener('click', event => {
                this.goToPage.call(that, page);
            });
        }

    }


}


const pag = new Paginator(10, 3,'paginator', render);

getData(pag.offset, pag.max).then(res => {
  pag.init(records.length, 10);
});

function changeMax(max){
    pag.changeMax(max);
}


function changeLocale() {
    pag.changeLocale({first: "Первая", last: "Последняя", next: "След", prev: "Пред"});
}


function render(page, offset, limit) {

    getData(offset, limit).then((res) => {
        const elem  = document.getElementById('data-list');
        elem.innerHTML = "";
        for(let i = 0; i < res.data.length; i++ ) {
           let el = document.createElement("p");
           el.innerHTML = `${res.data[i]}`;
           elem.appendChild(el);
        }
    });
}


function getData(offset, limit) {
  let res = [];
  for(let i = offset; i < offset + limit; i++ ) {
        res.push(records[i]);
    }

  return Promise.resolve({
    data: res,
    total: records.length
  });
}
#data-list p{
   margin: 2px;
   font-size:14px;
}

.change {
  cursor:pointer;
  color: green;
}



#paginator {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}

#paginator .page {
  min-width: 15px;
  text-align:center;
  border: 1px solid #999;
  cursor: pointer;
  padding: 5px;
}

#paginator .page.active {
  color: red;
}
<div  id="data-list">
</div>



<div id="paginator"></div>

<select onchange="changeMax(this.options[this.selectedIndex].value)">
   <option value="10"> 10</option>
    <option value="20"> 20</option>
</select>

<div class="change" onclick="changeLocale()">change locale to  rus</div>

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.