Pagination is one of those annoying features that aren't fun to implement, but that are pretty much essential for a good UI. Nowadays you can download any one of dozens of javascript libraries that will take care of most aspects of pagination for you on the client side. When I first tackled it for a client-side list I Googled it and found several different scripts that I couldn't make any sense of. While many of those solutions worked, they were hidden in 3rd-party libraries and only worked under certain conditions which I had little control over. So I decided to sit down and create my own implementation. It's a very simple implementation, but it covers the basics of what pagination is. And so I'll share it here today for your viewing pleasure. Feel free to modify it in any way that you want. Add numeric paging to it, reduce the amount of code, allow for multiple pagers per page, etc.

pagination

The basic process of pagination is usually the same regardless of the technology being used. We have a collection of data in some format. We then specify a set number of elements that we want to display per page. We render our pagination controls, such as next and previous. Depending on what page we're on, we cut a chunk of our 'data' out based on the current page and the number of elements per page, and we render our data. We then redraw our pager controls and we're good to go.

For numeric pagination, click here.

Define A Few Variables

Let's start by setting up a few variables to store some of our paging data, such as number of items per page and the current page we're on, and we'll have an Array to hold our data. We'll also create a sub section of our Array to store just the currently displayed elements.


var list = new Array();
var pageList = new Array();
var currentPage = 1;
var numberPerPage = 10;
var numberOfPages = 1;   // calculates the total number of pages

Our list variable will store our collection of data. This can be anything really. Strings, Integers, javascript objects. The currentPage variable will keep track of where we are in our pagination. numberPerPage dictates the amount of items to show per page. pageList plays a very important role in our script as it will keep track of the items to display for the current page. We don't need to store it separately, but depending on your data it can make the process easier and for our example it will make the process easier to follow. The numberOfPages is calculated on load and will tell us the total number of pages required to render our collection. This is really only necessary if we're going to be doing numeric pagination.

That should be enough to get us going with a quick example. Next up let's create some sample data to work with. An array of 200 integers should be enough to get the ball rolling.


1. Create A Test List (optional)

If you have data ready to go you can skip this step. Otherwise, run the function onLoad.


function makeList() {
    for (x = 0; x < 200; x++)
        list.push(x);
}


function load() {
    makeList();
}
    
window.onload = load;

2. Calculate Number of Pages

We'll need to know the number of pages in our application so that we can handle enabling and disabling the pager buttons accordingly. For example, getting to the last page will automatically disable the next and last buttons, etc. We can add this functionality to our load function.


function load(){
    makeList();
    numberOfPages = getNumberOfPages();
}


function getNumberOfPages() {
    return Math.ceil(list.length / numberPerPage);
}


3. Create Paging Buttons

We'll be making a first-next-previous-last pager to navigate through our pages. After each page is loaded a check will occur to verify the state of all the buttons, such as disabling the next button when the last page is reached.


<body>
<input type="button" id="first" onclick="firstPage()" value="first" />
<input type="button" id="next" onclick="nextPage()" value="next" />
<input type="button" id="previous" onclick="previousPage()" value="previous" />
<input type="button" id="last" onclick="lastPage()" value="last" />
</body>

Each button control will call a different function. The only real difference in each functions implementation is the value of the currentPage variable. After that we call loadList(), which is the function that will do all the work and draw our elements onto the screen.

For example, the nextPage function is implemented as follows:


function nextPage() {
    currentPage += 1;
    loadList();
}

While the previousPage function is as such:


function previousPage() {
    currentPage -= 1;
    loadList();
}

Here is the firstPage function


function firstPage() {
    currentPage = 1;
    loadList();
}

And last but not least, the lastPage function.


function lastPage() {
    currentPage = numberOfPages;
    loadList();
}

It's basically the same function called each time with change in a variable. For something this simple, inlining the script might be preferred.

4. LoadList()

Next up is splitting our data up into their appropriate page counterparts. First we calculate the index of our first element and of our last element for that particular page. Next up we call the slice function of our Array and tell it where to start slicing from and where to end. The result will be an Array with just the elements that we're currently looking for. The algorithm is pretty self-explanatory. You start at the current page, minus one, plus the page offset. And the end is just that start number plus the offset again. The 2 new functions at the bottom drawList and check will render the sublist and then update the pager buttons respectively.


function loadList() {
    var begin = ((currentPage - 1) * numberPerPage);
    var end = begin + numberPerPage;

    pageList = list.slice(begin, end);
    drawList();    // draws out our data
    check();         // determines the states of the pagination buttons
}

5. Draw The List

Since this is just a simple example to illustrate the idea, our drawList function will just spit out the values in our pageList Array.


function drawList() {
    document.getElementById("list").innerHTML = "";
    
    for (r = 0; r < pageList.length; r++) {
        document.getElementById("list").innerHTML += pageList[r] + "
"; } }

6. Update Button Statuses

So far we have an Array with our items to paginate through, and our control buttons that will determine which page we go to next. And we have our function that will set the elements for the current page that we are on. That's pretty much a fully working pagination module. But, we can do a bit better. After each new sublist is loaded we'll want to determine the state of the paging buttons (next, prev, first, last). For example, if we are on page 1, then our first and previous buttons should be disabled. We can run the following function after each new page list is generated.


function check() {
    document.getElementById("next").disabled = currentPage == numberOfPages ? true : false;
    document.getElementById("previous").disabled = currentPage == 1 ? true : false;
    document.getElementById("first").disabled = currentPage == 1 ? true : false;
    document.getElementById("last").disabled = currentPage == numberOfPages ? true : false;
}

7. Full Working Code

Here is the full working JS example for your copy/paste pleasure.


<script type="text/javascript">
    var list = new Array();
    var pageList = new Array();
    var currentPage = 1;
    var numberPerPage = 10;
    var numberOfPages = 0;

function makeList() {
    for (x = 0; x < 200; x++)
        list.push(x);

    numberOfPages = getNumberOfPages();
}
    
function getNumberOfPages() {
    return Math.ceil(list.length / numberPerPage);
}

function nextPage() {
    currentPage += 1;
    loadList();
}

function previousPage() {
    currentPage -= 1;
    loadList();
}

function firstPage() {
    currentPage = 1;
    loadList();
}

function lastPage() {
    currentPage = numberOfPages;
    loadList();
}

function loadList() {
    var begin = ((currentPage - 1) * numberPerPage);
    var end = begin + numberPerPage;

    pageList = list.slice(begin, end);
    drawList();
    check();
}
    
function drawList() {
    document.getElementById("list").innerHTML = "";
    for (r = 0; r < pageList.length; r++) {
        document.getElementById("list").innerHTML += pageList[r] + "<br/>";
    }
}

function check() {
    document.getElementById("next").disabled = currentPage == numberOfPages ? true : false;
    document.getElementById("previous").disabled = currentPage == 1 ? true : false;
    document.getElementById("first").disabled = currentPage == 1 ? true : false;
    document.getElementById("last").disabled = currentPage == numberOfPages ? true : false;
}

function load() {
    makeList();
    loadList();
}
    
window.onload = load;
</script>


<body>
    <div style="text-align:center;">
    <input type="button" id="first" onclick="firstPage()" value="first" />
    <input type="button" id="next" onclick="nextPage()" value="next" />
    <input type="button" id="previous" onclick="previousPage()" value="previous" />
    <input type="button" id="last" onclick="lastPage()" value="last" />

    <div id="list"></div>
    </div>
</body>

Working Example

Comments

edellucien
"Cheers! Thanks a lot, helped me to create the required pagination for my website. Working on it in order to add the display of numbered buttons to improve the display."
Well thank you. Very happy to hear it helped you out!
10/5/2016
Spenser
"Great resource! I needed to create pagination based on a custom table layout because I am using rowSpan. There aren't really any tools that offer pagination for a table that implements rowSpan, so I was able to use this by just changing up the makeList() and drawList() functions. Appreciate this solution."
Thanks Spenser! Definitely glad it helped you out!
3/1/2016