Implement Pagination with Vanilla JavaScript

How to Implement Pagination with Vanilla JavaScript?

Pagination is a common feature in web applications, allowing users to navigate through a large dataset or a list of items without overwhelming them with too much information at once.

Implementing pagination using JavaScript with API data is a crucial skill for web developers, as it can significantly enhance the user experience by breaking up content into manageable chunks.

In this article, we’ll walk through the steps to implement pagination in your web application using JavaScript with API data.

Prerequisites

Before we dive into the implementation, make sure you have the following prerequisites in place:

  1. Basic knowledge of HTML, CSS, and JavaScript.
  2. Access to an API that provides paginated data (e.g., a RESTful API).
  3. A text editor or Integrated Development Environment (IDE) to write and test your code.
  4. A web server to host your web application (optional).

HTML and CSS Setup

Let’s start by setting up the HTML structure for your paginated content. Create an HTML file with a container for your data and pagination controls. You can also add some minimal CSS for styling:

<!DOCTYPE html>
<html>
<body>
    <div class="container">
        <div id="data"></div>
        <div id="pagination"></div>
    </div>

    <script src="script.js"></script>
</body>
</html>

JavaScript Implementation

Now, let’s implement the pagination logic in JavaScript. Create a script.js file and follow these steps:

Step 1: Fetch API Data

You’ll need to fetch data from the API. You can use the fetch API to accomplish this. Replace YOUR_API_URL with the actual URL of the API you’re using.

const apiUrl = 'YOUR_API_URL';
const itemsPerPage = 10; // Number of items to display per page

async function fetchData() {
    try {
        const response = await fetch(apiUrl);
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error fetching data:', error);
    }
}

Step 2: Display Data

Create a function to display data on the page. This function should take the data and the current page as arguments and render the relevant data on the page.

function displayData(data, page) {
    const dataContainer = document.getElementById('data');
    dataContainer.innerHTML = ''; // Clear the container

    const start = (page - 1) * itemsPerPage;
    const end = start + itemsPerPage;

    const itemsToDisplay = data.slice(start, end);

    itemsToDisplay.forEach(item => {
        // Create and append elements to dataContainer
        const itemElement = document.createElement('div');
        itemElement.textContent = item.title; // Customize as needed
        dataContainer.appendChild(itemElement);
    });
}

Step 3: Create Pagination Controls

To create pagination controls, you need to calculate the total number of pages and create buttons to navigate between them.

function createPagination(data) {
    const paginationContainer = document.getElementById('pagination');
    paginationContainer.innerHTML = ''; // Clear the container

    const totalPages = Math.ceil(data.length / itemsPerPage);

    for (let i = 1; i <= totalPages; i++) {
        const button = document.createElement('button');
        button.textContent = i;
        button.addEventListener('click', () => displayData(data, i));
        paginationContainer.appendChild(button);
    }
}

Step 4: Initialize

To start the pagination, fetch the data, display the first page, and create pagination controls. You can add this to your script:

(async function () {
    const data = await fetchData();
    displayData(data, 1);
    createPagination(data);
})();

Putting It All Together

With these steps completed, you have a functional pagination system using JavaScript with API data.

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css@2/out/water.css" />
        <style>
            #data {
                font-size: 18px;
            }

            #pagNums,
            .pagination {
                display: flex;
                flex-wrap: wrap;
                gap: 5px;
            }
            .pagination button {
                padding: 10px 15px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <h1>Pagination: page - <span id="curPage">1</span></h1>
            <ul id="data"></ul>

            <div class="pagination">
                <div id="pagNums"></div>
            </div>
        </div>

        <script>
            const apiUrl = 'https://jsonplaceholder.typicode.com/posts';
            const itemsPerPage = 15; // Number of items to display per page
            let currentPage = 1;
            let totalPages = 0;
            const curPageEl = document.getElementById('curPage');

            async function fetchData() {
                try {
                    const response = await fetch(apiUrl);
                    const data = await response.json();
                    return data;
                } catch (error) {
                    console.error('Error fetching data:', error);
                }
            }
            function displayData(data, page) {
                currentPage = page;
                curPageEl.innerText = currentPage;
                const dataContainer = document.getElementById('data');
                dataContainer.innerHTML = ''; // Clear the container

                const start = (page - 1) * itemsPerPage;
                const end = start + itemsPerPage;

                const itemsToDisplay = data.slice(start, end);

                itemsToDisplay.forEach((item) => {
                    // Create and append elements to dataContainer
                    const itemElement = document.createElement('li');
                    itemElement.textContent = item.title; // Customize as needed
                    dataContainer.appendChild(itemElement);
                });
            }

            function createPagination(data) {
                const paginationContainer = document.getElementById('pagNums');
                paginationContainer.innerHTML = ''; // Clear the container

                // Calculating Total Pages
                totalPages = Math.ceil(data.length / itemsPerPage);

                // Implementing Next And Prev Buttons
                if (totalPages > 0) {
                    const nextBtn = document.createElement('button');
                    const prevBtn = document.createElement('button');
                    nextBtn.textContent = 'Next';
                    prevBtn.textContent = 'Prev';
                    nextBtn.addEventListener('click', () => {
                        if (totalPages >= currentPage + 1)
                            displayData(data, currentPage + 1);
                    });
                    prevBtn.addEventListener('click', () => {
                        if (0 < currentPage - 1)
                            displayData(data, currentPage - 1);
                    });

                    paginationContainer.insertAdjacentElement(
                        'beforebegin',
                        prevBtn
                    );
                    paginationContainer.insertAdjacentElement(
                        'afterend',
                        nextBtn
                    );
                }

                // Inserting Page numbers
                for (let i = 1; i <= totalPages; i++) {
                    const button = document.createElement('button');
                    button.textContent = i;
                    button.addEventListener('click', () =>
                        displayData(data, i)
                    );
                    paginationContainer.appendChild(button);
                }
            }

            (async function () {
                const data = await fetchData();
                displayData(data, 1);
                createPagination(data);
            })();
        </script>
    </body>
</html>

When you load your HTML file in a web browser, you should see the paginated data and pagination controls.


Remember that this is a basic example, and you can further customize and enhance it according to your specific needs, such as handling error states, adding loading indicators, or incorporating search functionality.

Pagination is a powerful tool for managing large datasets, and it greatly improves the user experience by keeping your application responsive and user-friendly.