How To Implement Pagination In Vanilla JavaScript

Pagination In 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. In this tutorial you will learn how to create pagination feature using vanilla JavaScript with source code.

1. HTML Structure for the Pagination Page

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>

2. JavaScript Code for Pagination

1. Fetching the dummy data from the jsonplaceholder.

https://jsonplaceholder.typicode.com/posts
// Define the API URL
const apiUrl = 'https://jsonplaceholder.typicode.com/posts';

// Number of posts to display per page
const itemsPerPage = 10;

// Function to fetch data from the API
async function fetchData() {
    try {
        // Fetch data from the API
        const response = await fetch(apiUrl);
        // Convert response to JSON format
        const data = await response.json();
        // Return the fetched data
        return data;
    } catch (error) {
        // Log an error if fetching fails
        console.error('Error fetching data:', error);
    }
}

2. Creating displayData() function for display the fetched data. This function should take the data and the current page as arguments and render the relevant data on the page.

// Function to display data on the page
function displayData(data, page) {
    // Get the container element to display data
    const dataContainer = document.getElementById('data');
    // Clear the container before displaying new data
    dataContainer.innerHTML = '';

    // Calculate the start and end index of items to display based on current page
    const start = (page - 1) * itemsPerPage;
    const end = start + itemsPerPage;

    // Extract items to display from the data array
    const itemsToDisplay = data.slice(start, end);

    // Iterate through the items to display
    itemsToDisplay.forEach(item => {
        // Create a new element for each item and append it to the data container
        const itemElement = document.createElement('div');
        // Customize the content of the item element, e.g., item.title
        itemElement.textContent = item.title; // Customize as needed
        dataContainer.appendChild(itemElement);
    });
}

3. Creating pagination controls that calculates the total number of pages and create buttons to navigate between them.

// Function to create pagination buttons based on the data length
function createPagination(data) {
    // Get the container element for pagination
    const paginationContainer = document.getElementById('pagination');
    // Clear the container before creating new pagination buttons
    paginationContainer.innerHTML = '';

    // Calculate the total number of pages needed based on the data length and items per page
    const totalPages = Math.ceil(data.length / itemsPerPage);

    // Loop to create pagination buttons for each page
    for (let i = 1; i <= totalPages; i++) {
        // Create a new button element for each page
        const button = document.createElement('button');
        // Set the button text to the page number
        button.textContent = i;
        // Add an event listener to the button to display corresponding data when clicked
        button.addEventListener('click', () => displayData(data, i));
        // Append the button to the pagination container
        paginationContainer.appendChild(button);
    }
}

4. Initialize the whole functionality through an anonymous function.

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

3. Combine all the Above JS Pagination Code Chunks “script.js”

// Define the API URL for fetching data
const apiUrl = "https://jsonplaceholder.typicode.com/posts";

// Number of items to display per page
const itemsPerPage = 15;

// Current page and total pages initialization
let currentPage = 1;
let totalPages = 0;

// Element to display current page number
const curPageEl = document.getElementById("curPage");

// Function to fetch data from the API
async function fetchData() {
    try {
        // Fetch data from the API
        const response = await fetch(apiUrl);
        // Convert response to JSON format
        const data = await response.json();
        // Return the fetched data
        return data;
    } catch (error) {
        // Log an error if fetching fails
        console.error("Error fetching data:", error);
    }
}

// Function to display data for a specific page
function displayData(data, page) {
    // Update current page
    currentPage = page;
    // Display current page number
    curPageEl.innerText = currentPage;
    // Get the container element to display data
    const dataContainer = document.getElementById("data");
    // Clear the container before displaying new data
    dataContainer.innerHTML = "";

    // Calculate the start and end index of items to display based on current page
    const start = (page - 1) * itemsPerPage;
    const end = start + itemsPerPage;

    // Extract items to display from the data array
    const itemsToDisplay = data.slice(start, end);

    // Iterate through the items to display
    itemsToDisplay.forEach((item) => {
        // Create a new list item element for each item and append it to the data container
        const itemElement = document.createElement("li");
        // Customize the content of the item element, e.g., item.title
        itemElement.textContent = item.title; // Customize as needed
        dataContainer.appendChild(itemElement);
    });
}

// Function to create pagination buttons and implement next/prev functionality
function createPagination(data) {
    // Get the container element for pagination
    const paginationContainer = document.getElementById("pagNums");
    // Clear the container before creating new pagination buttons
    paginationContainer.innerHTML = "";

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

    // Implementing Next And Prev Buttons
    if (totalPages > 0) {
        // Create next and prev buttons
        const nextBtn = document.createElement("button");
        const prevBtn = document.createElement("button");
        nextBtn.textContent = "Next";
        prevBtn.textContent = "Prev";
        // Add event listeners to next and prev buttons
        nextBtn.addEventListener("click", () => {
            if (totalPages >= currentPage + 1)
                displayData(data, currentPage + 1);
        });
        prevBtn.addEventListener("click", () => {
            if (0 < currentPage - 1) displayData(data, currentPage - 1);
        });

        // Insert next and prev buttons before and after pagination container
        paginationContainer.insertAdjacentElement("beforebegin", prevBtn);
        paginationContainer.insertAdjacentElement("afterend", nextBtn);
    }

    // Inserting Page numbers
    for (let i = 1; i <= totalPages; i++) {
        // Create a button element for each page number
        const button = document.createElement("button");
        button.textContent = i;
        // Add event listener to each button to display corresponding data
        button.addEventListener("click", () => displayData(data, i));
        // Append the button to the pagination container
        paginationContainer.appendChild(button);
    }
}

// Immediately Invoked Function Expression (IIFE) to fetch data, display initial page, and create pagination
(async function () {
    // Fetch data from the API
    const data = await fetchData();
    // Display data for the first page
    displayData(data, 1);
    // Create pagination buttons
    createPagination(data);
})();

Putting It All Together “index.html”

<!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>

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies to ensure that we give you the best experience on our website. Privacy Policy