How to Create Pagination in HTML, CSS, and JavaScript

Introduction

Pagination is crucial for improving the user experience by breaking up large amounts of content into smaller, manageable chunks. In this tutorial, you'll learn how to create a functional pagination system using HTML, CSS, and JavaScript. We will simulate the pagination of dummy data, allowing users to navigate between pages.

Development Steps

  1. Create the HTML Structure: Set up the basic structure for the pagination and data display.
  2. Style the Pagination Using CSS: Style the pagination links and the current page indicator.
  3. Implement Pagination Functionality with JavaScript: Use JavaScript to dynamically update the displayed data as users navigate between pages.

Step 1: Create the HTML Structure

We’ll create a basic structure for the pagination with a data display area. The ul will represent the pagination buttons, and a separate div will hold the content for each page.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pagination</title>
</head>
<body>

    <!-- Step 1: Pagination HTML structure -->
    <div id="data-container"></div>

    <div class="pagination">
        <ul id="pagination">
            <!-- Pagination buttons will be generated dynamically by JavaScript -->
        </ul>
    </div>

</body>
</html>

Explanation:

  • #data-container: This is where we’ll display the paginated content.
  • #pagination: The pagination buttons will be generated dynamically by JavaScript based on the number of pages.

Step 2: Style the Pagination Using CSS

We’ll style the pagination buttons to look clean and professional, while also highlighting the active page.

/* Step 2: Basic styles for pagination */
body {
    font-family: Arial, sans-serif;
}

#data-container {
    margin: 20px;
    font-size: 18px;
}

.pagination {
    display: flex;
    justify-content: center;
    margin: 20px 0;
}

.pagination ul {
    list-style-type: none;
    padding: 0;
    margin: 0;
    display: flex;
}

.pagination li {
    margin: 0 5px;
}

.pagination a {
    padding: 10px 15px;
    text-decoration: none;
    background-color: #f1f1f1;
    border: 1px solid #ddd;
    color: #333;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.pagination a:hover {
    background-color: #ddd;
}

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

.pagination a.disabled {
    pointer-events: none;
    color: #aaa;
    background-color: #eee;
    border-color: #ddd;
}

Explanation:

  • .pagination a.active: Highlights the current page with a green background and white text.
  • .pagination a.disabled: Disables the "Previous" and "Next" buttons when they are not needed.

Step 3: Implement Pagination Functionality with JavaScript

Now, we’ll write JavaScript to generate dummy data and implement the pagination logic.

JavaScript Code

<script>
    // Step 3: JavaScript Pagination Logic

    // Dummy data - an array of numbers to simulate content
    const dummyData = Array.from({ length: 100 }, (_, i) => `Item ${i + 1}`);
    const itemsPerPage = 10; // Number of items to show per page
    let currentPage = 1; // Start on the first page

    // Function to display the data for the current page
    function displayData(page) {
        const start = (page - 1) * itemsPerPage;
        const end = start + itemsPerPage;
        const items = dummyData.slice(start, end);
        
        const dataContainer = document.getElementById('data-container');
        dataContainer.innerHTML = items.map(item => `<p>${item}</p>`).join('');
    }

    // Function to create pagination buttons
    function createPagination(totalItems, itemsPerPage) {
        const totalPages = Math.ceil(totalItems / itemsPerPage);
        const pagination = document.getElementById('pagination');
        pagination.innerHTML = ''; // Clear the pagination list

        // Create the "Previous" button
        const prevClass = currentPage === 1 ? 'disabled' : '';
        pagination.innerHTML += `<li><a href="#" class="${prevClass}" onclick="goToPage(${currentPage - 1})">Previous</a></li>`;

        // Create page number buttons
        for (let i = 1; i <= totalPages; i++) {
            const activeClass = currentPage === i ? 'active' : '';
            pagination.innerHTML += `<li><a href="#" class="${activeClass}" onclick="goToPage(${i})">${i}</a></li>`;
        }

        // Create the "Next" button
        const nextClass = currentPage === totalPages ? 'disabled' : '';
        pagination.innerHTML += `<li><a href="#" class="${nextClass}" onclick="goToPage(${currentPage + 1})">Next</a></li>`;
    }

    // Function to handle page navigation
    function goToPage(page) {
        const totalPages = Math.ceil(dummyData.length / itemsPerPage);

        if (page < 1 || page > totalPages) return; // Prevent invalid pages

        currentPage = page; // Set the current page
        displayData(currentPage); // Update the displayed data
        createPagination(dummyData.length, itemsPerPage); // Update the pagination
    }

    // Initialize the pagination
    displayData(currentPage); // Display the first page of data
    createPagination(dummyData.length, itemsPerPage); // Create the pagination buttons
</script>

Explanation:

  • dummyData: An array containing 100 dummy items (e.g., "Item 1", "Item 2").
  • itemsPerPage: The number of items to display on each page.
  • displayData(page): Displays the content for the current page by slicing the dummyData array.
  • createPagination(totalItems, itemsPerPage): Dynamically generates the pagination buttons.
  • goToPage(page): Updates the page when a user clicks on a pagination button and prevents invalid page navigation.

Complete Code

Here's the full HTML, CSS, and JavaScript code for creating a functional pagination system:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pagination</title>
    <style>
        /* Basic styles for pagination */
        body {
            font-family: Arial, sans-serif;
        }

        #data-container {
            margin: 20px;
            font-size: 18px;
        }

        .pagination {
            display: flex;
            justify-content: center;
            margin: 20px 0;
        }

        .pagination ul {
            list-style-type: none;
            padding: 0;
            margin: 0;
            display: flex;
        }

        .pagination li {
            margin: 0 5px;
        }

        .pagination a {
            padding: 10px 15px;
            text-decoration: none;
            background-color: #f1f1f1;
            border: 1px solid #ddd;
            color: #333;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        .pagination a:hover {
            background-color: #ddd;
        }

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

        .pagination a.disabled {
            pointer-events: none;
            color: #aaa;
            background-color: #eee;
            border-color: #ddd;
        }
    </style>
</head>
<body>

    <!-- Pagination HTML structure -->
    <div id="data-container"></div>

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

    <script>
        // Dummy data - an array of numbers to simulate content
        const dummyData = Array.from({ length: 100 }, (_, i) => `Item ${i + 1}`);
        const itemsPerPage = 10; // Number of items to show per page
        let currentPage = 1; // Start on the first page

        // Function to display the data for the current page
        function displayData(page) {
            const start = (page - 1) * itemsPerPage;
            const end = start + itemsPerPage;
            const items = dummyData.slice(start, end);
            
            const dataContainer = document.getElementById('data-container');
            dataContainer.innerHTML = items.map(item => `<p>${item}</p>`).join('');
        }

        // Function to create pagination buttons
        function createPagination(totalItems, itemsPerPage) {
            const totalPages = Math.ceil(totalItems / itemsPerPage);
            const pagination = document.getElementById('pagination');
            pagination.innerHTML = ''; // Clear the pagination list

            // Create the "Previous" button
            const prevClass = currentPage === 1 ? 'disabled' : '';
            pagination.innerHTML += `<li><a href="#" class="${prevClass}" onclick="goToPage(${currentPage - 1})">Previous</a></li>`;

            // Create page number buttons
            for (let i = 1; i <= totalPages; i++) {
                const activeClass = currentPage === i ? 'active' : '';
                pagination.innerHTML += `<li><a href="#" class="${activeClass}" onclick="goToPage(${i})">${i}</a></li>`;
            }

            // Create the "Next" button
            const nextClass = currentPage === totalPages ? 'disabled' : '';
            pagination.innerHTML += `<li><a href="#" class="${nextClass}" onclick="goToPage(${currentPage + 1})">Next</a></li>`;
        }

        // Function to handle page navigation
        function goToPage(page) {
            const totalPages = Math.ceil(dummyData.length / itemsPerPage);

            if (page < 1 || page > totalPages) return; // Prevent invalid pages

            currentPage = page; // Set the current page
            displayData(currentPage); // Update the displayed data
            createPagination(dummyData.length, itemsPerPage); // Update the pagination
        }

        // Initialize the pagination
        displayData(currentPage); // Display the first page of data
        createPagination(dummyData.length, itemsPerPage); // Create the pagination buttons
    </script>

</body>
</html>

Output

You can play with the above HTML in Online HTML Editor and Compiler. Here is the output of the above HTML page.:

Conclusion

In this tutorial, you learned how to create a working pagination system using HTML, CSS, and JavaScript. This system dynamically updates the displayed data as users navigate through pages. By leveraging JavaScript, you can easily handle large datasets and create a more interactive user experience.

Comments