FOR DEVELOPERS

How to Implement Pagination in JavaScript

How to implement pagination in JavaScript

Pagination is a common feature in many web applications. It allows users to navigate through large sets of data by displaying only a subset of that data at a time. Implementing JavaScript pagination is relatively straightforward and in this article, we’ll explore how to do so as well as the best practices to follow.

We'll implement a simple pagination functionality that allows users to navigate through a list of items with a fixed number of items displayed per page. Let's get started!

Why use JavaScript pagination?

JavaScript pagination can provide several benefits to a website or application:

  • Firstly, it allows you to break up large amounts of content into manageable chunks, making it easier for users to navigate and find the information they need. This can improve user experience and engagement, as users are less likely to become overwhelmed or frustrated.
  • Additionally, it can reduce page load times by only loading a subset of content at a time, which can improve overall site performance and speed. This is especially important for mobile users who may have limited bandwidth or slower connections.
  • Finally, it allows you to dynamically update content without requiring a full page reload. This can create a smoother and more seamless user experience. Overall, JavaScript pagination is a powerful tool for improving usability, performance, and engagement on a website or application.

Examples of pagination

JavaScript provides several options for implementing pagination, including client-side and server-side approaches.

  • Client-side pagination involves rendering a limited number of items on the page and providing controls to move between pages. This approach is fast and efficient for small datasets but can be slow for larger ones.
  • Server-side pagination, on the other hand, involves fetching a specific subset of data from the server based on the current page number and the number of items per page. This approach is more suitable for larger datasets but requires more server resources.

Some popular pagination libraries in JavaScript include DataTables, React-Paginate, and Bootstrap Pagination.

How to implement pagination using JavaScript

HTML markup

Our HTML markup will contain a list of items and a container for the pagination controls. The HTML will look like this:

<div id="items">
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
    <li>Item 7</li>
    <li>Item 8</li>
    <li>Item 9</li>
    <li>Item 10</li>
  </ul>
</div>

<div id="pagination" class="pagination-container"></div>

Here, we have a list of 10 items contained within a <ul> element with an ID of "items". We also have a container element with an ID of "pagination" that we'll use to display the pagination controls. The class "pagination-container" is added for CSS styling purposes.

CSS styling

We'll use CSS to style the list items and pagination controls. Here's a basic CSS styling:

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}

li { padding: 10px; border: 1px solid #ccc; margin-bottom: 10px; }

.pagination-container { display: flex; justify-content: center; align-items: center; margin-top: 20px; }

.pagination { display: inline-flex; border-radius: 5px; overflow: hidden; }

.pagination a { color: black; padding: 8px 16px; text-decoration: none; border: 1px solid #ddd; border-right: none; background-color: #f1f1f1; transition: background-color 0.3s ease-in-out; }

.pagination a:first-child { border-top-left-radius: 5px; border-bottom-left-radius: 5px; }

.pagination a:last-child { border-right: 1px solid #ddd; border-top-right-radius: 5px; border-bottom-right-radius: 5px; }

.pagination a.active { background-color: #4caf50; color: white; border: none; }

.pagination a:hover:not(.active) { background-color: #ddd; }

JavaScript code

We'll use JavaScript to implement pagination functionality. We'll define a function paginate() that takes an array of items, the number of items per page, and the container element to display the pagination controls. The function will create and display the pagination controls and update the displayed items based on the selected page.

function paginate(items, itemsPerPage, paginationContainer) {
  let currentPage = 1;
  const totalPages = Math.ceil(items.length / itemsPerPage);

function showItems(page) { const startIndex = (page - 1) * itemsPerPage; const endIndex = startIndex + itemsPerPage; const pageItems = items.slice(startIndex, endIndex);

const itemsContainer = document.querySelector(&quot;#items&quot;);
itemsContainer.innerHTML = &quot;&quot;;

pageItems.forEach((item) =&gt; {
  const li = document.createElement(&quot;li&quot;);
  li.innerText = item;
  itemsContainer.appendChild(li);
});

}

function setupPagination() { const pagination = document.querySelector(paginationContainer); pagination.innerHTML = "";

for (let i = 1; i &lt;= totalPages; i++) {
  const link = document.createElement(&quot;a&quot;);
  link.href = &quot;#&quot;;
  link.innerText = i;

  if (i === currentPage) {
    link.classList.add(&quot;active&quot;);
  }

  link.addEventListener(&quot;click&quot;, (event) =&gt; {
    event.preventDefault();
    currentPage = i;
    showItems(currentPage);

    const currentActive = pagination.querySelector(&quot;.active&quot;);
    currentActive.classList.remove(&quot;active&quot;);
    link.classList.add(&quot;active&quot;);
  });

  pagination.appendChild(link);
}

}

showItems(currentPage); setupPagination(); }

We'll test the pagination functionality by calling the paginate() function with an array of items, the number of items per page, and the container element to display the pagination controls.

Let's call the paginate() function with some sample data.

const items = [
"Item 1",
"Item 2",
"Item 3",
"Item 4",
"Item 5",
"Item 6",
"Item 7",
"Item 8",
"Item 9",
"Item 10",
"Item 11",
"Item 12",
"Item 13",
"Item 14",
"Item 15",
"Item 16",
"Item 17",
"Item 18",
"Item 19",
"Item 20",
"Item 21",
"Item 22",
"Item 23",
"Item 24",
"Item 25",
"Item 26",
"Item 27",
"Item 28",
"Item 29",
"Item 30",
"Item 31",
"Item 32",
"Item 33",
"Item 34",
"Item 35",
];

const itemsPerPage = 5; const paginationContainer = "#pagination";

paginate(items, itemsPerPage, paginationContainer);

When we run the above code, it will display the first page of items with pagination controls.

You can try clicking on the pagination controls to navigate to different pages and see how the displayed items change.

Pagination methods

Method 1: Basic pagination

The simplest way to implement pagination in JavaScript is to use a for loop to iterate over the data and display only a certain number of items per page. For example, if there’s an array of 100 items and we want to display 10 items per page, we can use the following code:

var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100];
var itemsPerPage = 10;
var currentPage = 1;

for (var i = 0; i < data.length; i++) { if (i >= (currentPage - 1) * itemsPerPage && i < currentPage * itemsPerPage) { console.log(data[i]); } }

This will display the first 10 items of the data array on the first page, the next 10 items on the second page, and so on.

Method 2: Advanced pagination

A more advanced way to implement JavaScript pagination is to use a library or framework that offers built-in pagination features. For example, the AngularJS framework has a directive called "ng-repeat" that can be used to paginate data. The following code demonstrates how to use it to paginate an array of data:

<div ng-app="myApp" ng-controller="myCtrl">
  <div ng-repeat="item in data | pagination: currentPage : itemsPerPage">
    {{item}}
  </div>
  <button ng-click="previousPage()">Previous</button>
  <button ng-click="nextPage()">Next</button>
</div>
var app = angular.module("myApp", ["pagination"]);
app.controller("myCtrl", function($scope) {
  $scope.data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64];
  $scope.itemsPerPage = 10;
  $scope.currentPage = 1;

$scope.previousPage = function() { if ($scope.currentPage > 1) { $scope.currentPage--; } }

$scope.nextPage = function() { if ($scope.currentPage < Math.ceil($scope.data.length / $scope.itemsPerPage)) { $scope.currentPage++; } } });

This code uses the "pagination" filter provided by the AngularJS framework to paginate the data array. It also includes previous and next buttons to allow users to navigate through the pages.

Conclusion

We’ve learned how to implement pagination in JavaScript and defined a function that takes an array of items, the number of items per page, and the container element to display the pagination controls. We also tested our pagination functionality by calling the paginate() function with sample data. Note that the code can be customized according to various needs to implement pagination in a web application.

Pagination is a useful technique for displaying large amounts of data in a manageable and organized way. There are different ways to implement it, from using basic loops to advanced libraries and frameworks. When choosing a method, it is important to consider your project's specific needs and the data's complexity. By following the best practices and techniques discussed in this article, you can create a powerful and user-friendly pagination system in JavaScript.

Author

  • How to Implement Pagination in JavaScript

    Bonaventure Ogeto

    Bonaventure Ogeto is the Founder of Hojaleaks.com, a platform dedicated to promoting software development education through open-source content. Bonaventure is also a Software Developer, Technical Writer, Mentor, Author, and Debater from Nairobi, Kenya who is building products and developing solutions that help increase productivity and accelerate performance.

Frequently Asked Questions

Pagination in JavaScript refers to the process of dividing a large set of data into smaller, more manageable pieces called pages. This makes it easier for users to navigate through the data and find what they are looking for. It is important because it improves the performance of the application by reducing the amount of data that needs to be loaded at once.

There are several ways to do this. One is to use a server-side API that returns a subset of data based on a set of parameters, such as the page number and the number of items per page. Another approach is to use a client-side library or framework like React or Angular that includes built-in support for pagination. Alternatively, you can implement pagination manually by using JavaScript to manipulate the DOM and load data as needed.

Some best practices for implementing pagination in JavaScript include:

  • Limiting the number of items per page to a reasonable amount to avoid overwhelming the user with too much data at once.
  • Providing clear navigation controls, such as previous and next buttons, and displaying the current page number and total number of pages.
  • Implementing caching to improve performance by storing previously loaded data in memory and avoiding unnecessary API requests.
  • Ensuring that the pagination logic is accessible and works well for users who rely on screen readers or other assistive technologies.
  • Testing the pagination functionality thoroughly to ensure that it works correctly and reliably across different browsers and devices.
View more FAQs
Press

Press

What’s up with Turing? Get the latest news about us here.
Blog

Blog

Know more about remote work. Checkout our blog here.
Contact

Contact

Have any questions? We’d love to hear from you.

Hire remote developers

Tell us the skills you need and we'll find the best developer for you in days, not weeks.