Thursday, April 24, 2014

How to create a pager in javascript

1. Take a piece of paper and draw


2. Test it on paper


3. Pseudo-code

// Check if there are pages at all
if (pagesTotal < 1) {
 return;
}

// First visible page
firstVisiblePageNo = pageNo - visiblePositions / 2 + 1 = 12

// Adjsut first visible page
if (firstVisiblePageNo < 1) {
 firstVisiblePageNo = 1
}

// Number of pages in sequence
sequentialPages = visiblePositions
lastPageNoInSequence = firstVisiblePageNo + visiblePositions - 1 = 17

// Adjust last page in sequence
if (lastPageNoInSequence > pagesTotal) {
 lastPageNoInSequence = pagesTotal

 // If reached the last pages on the right, get more pages from the left
 if (lastPageNoInSequence - firstVisiblePageNo + 1 < visiblePositions) {
  firstVisiblePageNo = lastPageNoInSequence - visiblePositions + 1;
 }
 // Adjsut first visible page
 if (firstVisiblePageNo < 1) {
  firstVisiblePageNo = 1
 }
}
if (lastPageNoInSequence < pagesTotal) {
 sequentialPages -= 2;
 showEllipsis = true
}

for (currentPageNo = firstVisiblePageNo; currentPageNo <= lastPageNoInSequence; currentPageNo++) {
 render page(currentPageNo)
}

if (showEllipsis) {
 render ellipsis
 render page(pagesTotal)
}

4. Debug it on paper (or in notepad)

1 2 {3 4 [5] 6} 7 8 9 10 11 12 13 14 15

{1 [2] 3 4 5 6} 7 8 9 10 11 12 13 14 15

{1 [2] 3 4}

1 2 3 4 5 6 7 8 9 {10 11 12 13 [14] 15}

1 2 3 [4] 5 6 7

// Const
visiblePositions = 6

// Given
pageNo = 14
pagesTotal = 15

5. Code it

6. Test it



7. Enjoy


Do you like the result?

Feedback appreciated!

No comments:

Post a Comment