How to Create Simple Pagination in JavaScript

Anika Tabassum Era Feb 02, 2024
  1. Custom Pagination Function to Paginate Webpages
  2. Use of Jquery Plugin pagination.js to Surf on Webpages
How to Create Simple Pagination in JavaScript

In JavaScript, we often define our preferred function scopes to extract certain activities. Pagination in JavaScript can be manually scripted with the combination of multiple functions.

We will demonstrate how to create pagination to surf from page to page. We will create basic pagination functions to operate it, and we will also see another example with the jquery plugin pagination.js that will make our coding experience easier.

Custom Pagination Function to Paginate Webpages

We will initially declare the object that has our data. The next step is to count each data and how much we wish to preview on one page. We will also get the total number of pages on our webpage in this process.

After the totNumPages function calculates our total amount of pages, we will create the base function to hit prev and next.

Let’s check the code block to have a clear conception.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
<div id="TableList"></div>
<a href="javascript:prevPage()" id="btn_prev">Prev</a>&nbsp;
<a href="javascript:nextPage()" id="btn_next">Next</a><br>
page: <span id="page"></span>
</body>
</html>
var obj = [
  {number: 'Number 1'}, {number: 'Number 2'}, {number: 'Number 3'},
  {number: 'Number 4'}, {number: 'Number 5'}, {number: 'Number 6'},
  {number: 'Number 7'}, {number: 'Number 8'}, {number: 'Number 9'},
  {number: 'Number 10'}, {number: 'Number 11'}, {number: 'Number 12'},
  {number: 'Number 13'}, {number: 'Number 14'}, {number: 'Number 15'}
];
var current_page = 1;
var obj_per_page = 3;
function totNumPages() {
  return Math.ceil(obj.length / obj_per_page);
}

function prevPage() {
  if (current_page > 1) {
    current_page--;
    change(current_page);
  }
}
function nextPage() {
  if (current_page < totNumPages()) {
    current_page++;
    change(current_page);
  }
}
function change(page) {
  var btn_next = document.getElementById('btn_next');
  var btn_prev = document.getElementById('btn_prev');
  var listing_table = document.getElementById('TableList');
  var page_span = document.getElementById('page');
  if (page < 1) page = 1;
  if (page > totNumPages()) page = totNumPages();
  listing_table.innerHTML = '';
  for (var i = (page - 1) * obj_per_page; i < (page * obj_per_page); i++) {
    listing_table.innerHTML += obj[i].number + '<br>';
  }
  page_span.innerHTML = page;
  if (page == 1) {
    btn_prev.style.visibility = 'hidden';
  } else {
    btn_prev.style.visibility = 'visible';
  }
  if (page == totNumPages()) {
    btn_next.style.visibility = 'hidden';
  } else {
    btn_next.style.visibility = 'visible';
  }
}
window.onload = function() {
  change(1);
};

Output:

custom_pagination

In this case, the change function plays a vital role in visualizing the navigation and the object limitations per page. Also, the visibility of prev and next clickables on the first and last page. Whenever the page is loaded and after any reload, the default page is set to page 1.

Use of Jquery Plugin pagination.js to Surf on Webpages

The Jquery plugin has made the way easier to implement pagination in web pages. You need to add the CDN for the plugin in the header section, easily importing predefined conventions to tackle pagination creation.

In the example below, we will define a datasource. The datasource can be initialized as an array, object, URL, JSON, and similar formats. Multiple parameters work within this plugin. For instance, we can add pageSize:10 to select entries per page.

Let’s dig into the code block first.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>pagination example</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/paginationjs/2.1.4/pagination.min.js"></script>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/paginationjs/2.1.4/pagination.css"/>
</head>
<body>

<div>
    <section>
        <div id="container"></div>
        <div id="pagination"></div>
    </section>
</div>

<script>
    $(function () {
        let container = $('#pagination');
        container.pagination({
            dataSource: [
{number: "Number 1"},
{number: "Number 2"},
{number: "Number 3"},
{number: "Number 4"},
{number: "Number 5"},
{number: "Number 6"},
{number: "Number 7"},
{number: "Number 8"},
{number: "Number 9"},
{number: "Number 10"},
{number: "Number 11"},
{number: "Number 12"},
{number: "Number 13"},
{number: "Number 14"},
{number: "Number 15"},
{number: "Number 16"},
{number: "Number 17"},
            ],
            pageSize: 5,
            callback: function (data, pagination) {
                var dataHtml = '<ul>';

                $.each(data, function (index, item) {
                    dataHtml += '<li>' + item.number + '</li>';
                });

                dataHtml += '</ul>';

                $("#container").html(dataHtml);
            }
        })
    })
</script>
</body>
</html>

Output:

pagination_plugin_jquery

The code gets smaller, and the effort on generating functions is lessened. All that requires is to focus on the keywords or constructor defining the specified parameters to change the navigation from page to page swiftly.

For a more detailed explanation and usage of the plugin, check the documentation here.

Anika Tabassum Era avatar Anika Tabassum Era avatar

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

LinkedIn Facebook