Menu

Add Pagination To Any Table In JavaScript

Add Pagination To Any Table In JavaScript

Pagination is one of those things that everyone hates implementing on their websites, and that we avoid doing until the data size calls for it. Or until the page is so long that the scroll wheel breaks off and the browser crashes. And for good reason. It's a somewhat tedious and needlessly complicated task normally. But a very much needed tedious and complicated task. The following script is designed to handle any and all client side pagination for HTML tables once and for all.

Add Pagination To Any Table In JavaScript

For a closer look at how the pagination logic works, feel free to check out my other blog post right over here.

Feel free to use it and modify in any way that you wish as long as it helps you on your coding journey. All I ask, is that you throw some kind words my way if you do.

Before we start, if you are relatively new to JavaScript, then I recommend Web Design with HTML, CSS, JavaScript and jQuery as a good set of books and a good starting point to get you started.

And here is a quick example of the pagination in action for your viewing pleasure.

2 rows per page
Index Name Address Phone
1 bob s. 123 fake st 333-333-3333
2 steve q. 123 fake st 333-333-3333
3 mary m s. 123 fake st 333-333-3333
4 nancy s. 123 fake st 333-333-3333
5 nancy s. 123 fake st 333-333-3333
6 nancy s. 123 fake st 333-333-3333
7 nancy s. 123 fake st 333-333-3333

How it works

The entire process is very simple and obfuscates much of the complexity from the developer. Just add the script to your site and follow the following steps, and you'll have instant client side pagination, in under 100 lines of code.

1. Add the pagination class to each table that you want to add a pagination to.

2. Set the number of record elements per page, per table, in a dataset value named data-pagecount as such:

<table class="pagination" data-pagecount="3">

And that is it. Pagination complete as this script handles the rendering logic. Here are a few more examples of it in action using different data set sizes.

2 records per page
Index Name Address Phone
1 bob s. 123 fake st 333-333-3333
2 bob s. 123 fake st 333-333-3333
3 bob s. 123 fake st 333-333-3333
4 bob s. 123 fake st 333-333-3333

3 records per page
Index Name Address Phone
1 bob s. 123 fake st 333-333-3333
2 bob s. 123 fake st 333-333-3333
3 bob s. 123 fake st 333-333-3333
4 bob s. 123 fake st 333-333-3333

This is solely a client side implementation I must mention again and suited for small data sets. If you're dealing with thousands of records, then for sure you will need a server side implementation. Which I will cover in a future post.

In the meantime however, enjoy the script and use it as you will. Happy coding!


<script>
var perPage = 20;

function genTables() {
    var tables = document.querySelectorAll(".pagination");
    for (var i = 0; i < tables.length; i++) {
        perPage = parseInt(tables[i].dataset.pagecount);
        createFooters(tables[i]);
        createTableMeta(tables[i]);
        loadTable(tables[i]);
    }
}

// based on current page, only show the elements in that range
function loadTable(table) {
    var startIndex = 0;

    if (table.querySelector('th'))
        startIndex = 1;

	console.log(startIndex);

    var start = (parseInt(table.dataset.currentpage) * table.dataset.pagecount) + startIndex;
    var end = start + parseInt(table.dataset.pagecount);
    var rows = table.rows;

    for (var x = startIndex; x < rows.length; x++) {
        if (x < start || x >= end)
            rows[x].classList.add("inactive");
        else
            rows[x].classList.remove("inactive");
    }
}

function createTableMeta(table) {
    table.dataset.currentpage = "0";
}

function createFooters(table) {
    var hasHeader = false;
    if (table.querySelector('th'))
        hasHeader = true;

    var rows = table.rows.length;

    if (hasHeader)
        rows = rows - 1;

    var numPages = rows / perPage;
    var pager = document.createElement("div");

    // add an extra page, if we're 
    if (numPages % 1 > 0)
        numPages = Math.floor(numPages) + 1;

    pager.className = "pager";
    for (var i = 0; i < numPages ; i++) {
        var page = document.createElement("div");
        page.innerHTML = i + 1;
        page.className = "pager-item";
        page.dataset.index = i;

        if (i == 0)
            page.classList.add("selected");

        page.addEventListener('click', function() {
            var parent = this.parentNode;
            var items = parent.querySelectorAll(".pager-item");
            for (var x = 0; x < items.length; x++) {
                items[x].classList.remove("selected");
            }
            this.classList.add('selected');
            table.dataset.currentpage = this.dataset.index;
            loadTable(table);
        });
        pager.appendChild(page);
    }

    // insert page at the top of the table
    table.parentNode.insertBefore(pager, table);
}

window.addEventListener('load', function() {
    genTables();
});
</script>

Walter G. author of blog post
Walter Guevara is a Computer Scientist, software engineer, startup founder and previous mentor for a coding bootcamp. He has been creating software for the past 20 years.

Get the latest programming news directly in your inbox!

Have a question on this article?

You can leave me a question on this particular article (or any other really).

Ask a question

Community Comments

thatsoftwaredude.com logo
Walt
12/26/2018 12:42:43 PM
Any improvements you can add to the script, feel free to list them here!
J
Jason
9/18/2019 9:38:29 AM
How difficult is it to add a search to a paginated table? https://www.w3schools.com/howto/howto_js_filter_table.asp this one only filters out the current page.
thatsoftwaredude.com logo
Walt
9/18/2019 11:00:44 AM
That's a great question. It's a bit more involved than the w3 example. But essentially, you would need to rebuild the pagination bar each time you filter. Something that I will definitely add to this script. Many thanks for pointing that out Jason!
J
Jason
9/18/2019 12:58:39 PM
I did get the search to work, probably not the most elegant solution: added the W3 function to the top of your script and changed the FOR loop in your loadTable function to edit the style instead of the class. if (x < start || x >= end) rows[x].style.display = "none"; else rows[x].style.display = ""; For some reason couldn't get it to work by editing the W3 function.
N
Nihar
11/14/2019 9:18:25 PM
I'm working on .Net MVC right now. I just created a sample project to test the pagination and it also includes the database. Now I can list out the records but not with pagination. I've applied this very same code but didn't work. Can you help me out with this or can you add code that includes the database concept? Thank You!!!
thatsoftwaredude.com logo
Walt
11/18/2019 11:39:36 AM
A few things to check. Be sure that the page has fully loaded first before running the script. And be sure that the table has the 'pagination' class and the data-pagecount attribute set. If it isn't rendering, check the browser console and see if there any JS errors there!
c
coder
7/20/2020 3:25:07 AM
i'm just working on some table and i want to use this. how can i add prev and next buttons with this approach?
Ad Unit

Current Poll

Total Votes:
Q:
Submit

Add a comment