The Wayback Machine - https://web.archive.org/web/20240926162353/https://www.geeksforgeeks.org/create-a-pagination-using-html-css-and-javascript/
Open In App

Create a Pagination using HTML CSS and JavaScript

Last Updated : 30 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will create a working pagination using HTML, CSS, and JavaScript. Pagination, a widely employed user interface­ pattern, serves the purpose of dividing extensive­ data or content into more manageable­ portions. It allows users the ability to effortle­ssly navigate through numerous content pages, facilitating their search for specific information.

Create-a-Pagination-in-HTML-CSS-&-JavaScript

Approach to Create a Pagination with HTML CSS & JavaScript

To create a pagination system, we’ll follow these steps:

  • The HTML structure­ should be established for the­ page, incorporating a container for the ite­ms and pagination controls. This ensures a well-organize­d layout that enhances user e­xperience.
  • CSS Styling: Apply basic CSS styles to improve the appearance of the items and pagination buttons.
  • JavaScript Functionality: The task at hand involve­s writing JavaScript functions to effectively manage­ pagination logic. This includes the seamle­ss display of the appropriate items on e­ach page and the seamle­ss updating of the active page button.
  • Event Listeners: Attach event listeners to the pagination buttons to allow users to navigate between pages.

Example: In this JavaScript code, It begins by calculating the total numbe­r of pages based on the quantity of cards pe­r page. Two essential functions are­ then defined: displayPage­(page) controls which cards are displayed for the­ current page, while update­Pagination() adjusts the pagination buttons and page numbers base­d on the current page and total page­s. Furthermore, eve­nt listeners have be­en included for the “Pre­vious,” “Next,” and page number buttons to facilitate­ navigation.

HTML
<!-- index.html -->
<!DOCTYPE html> 
<html lang="en"> 

<head> 
    <meta charset="UTF-8"> 
    <meta name="viewport" content= 
        "width=device-width, initial-scale=1.0"> 
    <title>Pagination Example</title> 
    <link rel="stylesheet" href="style.css"> 
</head> 

<body> 
    <div id="data-container"> 
        <h1> Pagination in HTML CSS & JavaScript</h1> 
        <div class="card-container"> 
            <div class="card"> 
                <img src= 
"https://media.geeksforgeeks.org/img-practice/banner/mern-full-stack-development-classroom-thumbnail.png?v=19630"
                    alt="Image 1"> 
                <h3>mern full stack development classroom</h3> 
                <p>This is the content of Card 1.</p> 
            </div> 
            <div class="card"> 
                <img src= 
"https://media.geeksforgeeks.org/img-practice/banner/devops-live-thumbnail.png?v=19630"
                    alt="Image 2"> 
                <h3>Dev Ops Live</h3> 
                <p>This is the content of Card 2.</p> 
            </div> 
            <div class="card"> 
                <img src= 
"https://media.geeksforgeeks.org/img-practice/banner/gate-data-science-and-artificial-intelligence-da-2024-thumbnail.png?v=19630"
                    alt="Image 3"> 
                <h3>Gate Date science and artificial intelligence</h3> 
                <p>This is the content of Card 3.</p> 
            </div> 
            <div class="card"> 
                <img src= 
"https://media.geeksforgeeks.org/img-practice/banner/gate-crash-course-2024-thumbnail.png?v=19630"
                    alt="Image 4"> 
                <h3>gate crash course 2024 </h3> 
                <p>This is the content of Card 4.</p> 
            </div> 
            <div class="card"> 
                <img src= 
"https://media.geeksforgeeks.org/img-practice/banner/complete-test-series-product-companies-thumbnail.png?v=19631"
                    alt="Image 5"> 
                <h3>complete test series product companies</h3> 
                <p>This is the content of Card 5.</p> 
            </div> 
            <div class="card"> 
                <img src= 
"https://media.geeksforgeeks.org/img-practice/banner/dsa-to-development-coding-guide-thumbnail.png?v=19630"
                    alt="Image 6"> 
                <h3>dsa to development coding guide</h3> 
                <p>This is the content of Card 6.</p> 
            </div> 
            <div class="card"> 
                <img src= 
"https://media.geeksforgeeks.org/img-practice/banner/geeks-classes-live-thumbnail.png?v=19630"
                    alt="Image 7"> 
                <h3>geeks classes live</h3> 
                <p>This is the content of Card 7.</p> 
            </div> 
            <div class="card"> 
                <img src= 
"https://media.geeksforgeeks.org/img-practice/banner/dsa-interview-preparation-classroom-thumbnail.png?v=19631"
                    alt="Image 8"> 
                <h3>dsa interview preparation classroom</h3> 
                <p>This is the content of Card 8.</p> 
            </div> 
            <div class="card"> 
                <img src= 
"https://media.geeksforgeeks.org/img-practice/banner/complete-interview-preparation-thumbnail.png?v=19631"
                    alt="Image 9"> 
                <h3>complete interview preparation</h3> 
                <p>This is the content of Card 9.</p> 
            </div> 
            <div class="card"> 
                <img src= 
"https://media.geeksforgeeks.org/img-practice/banner/Data-Structures-With-Python-thumbnail.png?v=19631"
                    alt="Image 10"> 
                <h3>Data Structures With Python</h3> 
                <p>This is the content of Card 10.</p> 
            </div> 
            <!-- Add more cards as needed -->
        </div> 
    </div> 

    <div class="pagination" id="pagination"> 
        <a href="#" id="prev">Previous</a> 
        <a href="#" class="page-link" data-page="1">1</a> 
        <a href="#" class="page-link" data-page="2">2</a> 
        <a href="#" class="page-link" data-page="3">3</a> 
        <a href="#" id="next">Next</a> 
        <p id="page-numbers"> </p> 
    </div> 

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

</html>
CSS
/* style.css */
body {
    font-family: Arial, sans-serif;
    margin: 3rem;
}

.container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
}

.pagination {
    text-align: center;
    margin-top: 2rem;
}

.pagination a {
    color: #007BFF;
    padding: 8px 16px;
    text-decoration: none;
    border: 1px solid #007BFF;
    margin: 0 5px;
    border-radius: 4px;
}

.pagination a:hover {
    background-color: #007BFF;
    color: white;
}

.pagination .active {
    background-color: #007BFF;
    color: white;
}

.card-container {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
}

.card {
    border: 1px solid #ddd;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 2px 20px 0px rgba(0, 0, 0, 0.1);
    background-color: #fff;
    text-align: center;
}

.card img {
    max-width: 100%;
    height: auto;
    margin-bottom: 10px;
    border-radius: 10px;
}

h3 {
    margin-top: 10px;
    font-size: 18px;
    text-transform: capitalize;
}

h1 {
    text-align: center;
    margin: 2rem;
}

p {
    font-size: 14px;
}

#page-numbers {
    margin-top: 20px;
    font-size: 16px;
}
JavaScript
//script.js 
const cardsPerPage = 4; // Number of cards to show per page 
const dataContainer = document.getElementById('data-container'); 
const pagination = document.getElementById('pagination'); 
const prevButton = document.getElementById('prev'); 
const nextButton = document.getElementById('next'); 
const pageNumbers = document.getElementById('page-numbers'); 
const pageLinks = document.querySelectorAll('.page-link'); 

const cards = 
    Array.from(dataContainer.getElementsByClassName('card')); 

// Calculate the total number of pages 
const totalPages = Math.ceil(cards.length / cardsPerPage); 
let currentPage = 1; 

// Function to display cards for a specific page 
function displayPage(page) { 
    const startIndex = (page - 1) * cardsPerPage; 
    const endIndex = startIndex + cardsPerPage; 
    cards.forEach((card, index) => { 
        if (index >= startIndex && index < endIndex) { 
            card.style.display = 'block'; 
        } else { 
            card.style.display = 'none'; 
        } 
    }); 
} 

// Function to update pagination buttons and page numbers 
function updatePagination() { 
    pageNumbers.textContent = 
        `Page ${currentPage} of ${totalPages}`; 
    prevButton.disabled = currentPage === 1; 
    nextButton.disabled = currentPage === totalPages; 
    pageLinks.forEach((link) => { 
        const page = parseInt(link.getAttribute('data-page')); 
        link.classList.toggle('active', page === currentPage); 
    }); 
} 

// Event listener for "Previous" button 
prevButton.addEventListener('click', () => { 
    if (currentPage > 1) { 
        currentPage--; 
        displayPage(currentPage); 
        updatePagination(); 
    } 
}); 

// Event listener for "Next" button 
nextButton.addEventListener('click', () => { 
    if (currentPage < totalPages) { 
        currentPage++; 
        displayPage(currentPage); 
        updatePagination(); 
    } 
}); 

// Event listener for page number buttons 
pageLinks.forEach((link) => { 
    link.addEventListener('click', (e) => { 
        e.preventDefault(); 
        const page = parseInt(link.getAttribute('data-page')); 
        if (page !== currentPage) { 
            currentPage = page; 
            displayPage(currentPage); 
            updatePagination(); 
        } 
    }); 
}); 

// Initial page load 
displayPage(currentPage); 
updatePagination();

Output:

p1-ezgifcom-optimize

Previous Article
Next Article

Similar Reads

Create a Pagination Component using HTML CSS and JavaScript
In this article, we are going to create a pagination component using HTML, CSS, and JavaScript. Websites may need multiple pages to display the items for easier navigation and better user experiences. If you are looking to display large amounts of data on your site, like a blog, charts, or graphs that show information about the same data set, you w
3 min read
Create Pagination UI Using React And Tailwind CSS
When working with huge data sets in online applications, pagination is an essential feature. It makes a lengthy list of items easier to browse through by dividing them into digestible parts. This article will tell you how to use Tailwind CSS for styling and React for front-end functionality to create a pagination user interface. Prerequisites React
3 min read
How to make a Pagination using HTML and CSS ?
Creating pagination is quite simple, you can easily do that by using Bootstrap, and JavaScript. However, in this article, we will use HTML and CSS to create pagination.  Pagination is helpful when the website contains lots of content on a single page, and a single page will not look good with all those topics together. Few websites use the scroll t
3 min read
How to Create a Transition Effect on Hover Pagination using CSS ?
In web development, pagination is a common feature used to navigate through a large set of data or content. Adding a transition effect on hover to pagination buttons can enhance user interaction and provide visual feedback. ApproachIn this approach, we are going to use CSS transitions. It enables smooth changes in CSS property values over a specifi
1 min read
How to we create Pagination in Materialize CSS ?
Materialize CSS is a front-end UI library that is created by Google using the combination of HTML, CSS, and JavaScript. It is basically a design language that combines classic design along with modern innovations and technology. The purpose of Google behind developing Materialize CSS is to provide a unified system design for all their products acro
3 min read
How to Create Pagination in Node.js using Skip and Limit ?
Creating pagination in Node.js using the skip and limit methods. This approach efficiently retrieves specific data subsets from a database, improving performance and user experience by loading content in manageable segments rather than all at once. What is Pagination?Pagination is a very helpful method. This allows the client to fetch data in pages
4 min read
How to Change the Size of the Pagination using CSS ?
Pagination is an important user interface component that enables navigation through a set of pages. We can customize this element by adjusting its size. These are the two different approaches to customize and change the pagination size using CSS: Table of Content Using font-size PropertyUsing ScalingUsing font-size PropertyIn this approach, we are
3 min read
How to Add Hoverable Pagination using CSS ?
Pagination is a common technique for controlling content that covers multiple pages. Hoverable pagination provides a sleek alternative to traditional pagination styles by enabling users to preview the content without clicking by hovering over the pagination elements. Traditional pagination styles require users to click through numbered links to nav
2 min read
How to create pagination in Bootstrap 4 ?
Bootstrap is a free and open-source tool collection for creating responsive websites and web applications. It is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites. It solves many problems which we had once, one of which is the cross-browser compatibility issue. Pagination is an element used to ind
5 min read
CSS Pagination
Pagination is the process of dividing the document into pages and providing them with numbers. Types of Pagination: There are many types of pagination in CSS. Some of them are given below: Simple PaginationActive and Hoverable PaginationRounded Active and Hoverable ButtonsHoverable Transition EffectBordered PaginationRounded Border PaginationCenter
7 min read
Primer CSS Previous/Next Pagination
Primer CSS is a free open-source CSS framework that is built upon systems that create the foundation of the basic style elements such as spacing, typography, and color. This systematic method makes sure our patterns are steady and interoperable with every other. Its approach to CSS is influenced by Object-Oriented CSS principles, functional CSS, an
2 min read
Materialize CSS Pagination
Pagination is used to separate the content into discrete pages that is short and easy to understand. Materialize CSS provide classes to create a pagination bar that holds the links to the other pages. The pagination class is used to set the <ul> list element as a pagination component. The pages that have to be shown are defined inside this co
2 min read
Foundation CSS Kitchen Sink Pagination
Foundation CSS is the frontend framework of CSS that is used to build responsive websites, apps, and emails that work perfectly on any device. It is written using HTML, CSS, and Javascript and is used by many famous companies like Amazon, Facebook, eBay, etc. It uses packages like Grunt and Libsass for fast coding and controlling and Saas compiler
2 min read
Foundation CSS Pagination Basics
Foundation CSS is an open-source & responsive front-end framework built by ZURB foundation in September 2011, that makes it easy to design beautiful responsive websites, apps, and emails that look amazing & can be accessible to any device. It is used by many companies such as Facebook, eBay, Mozilla, Adobe, and even Disney. The framework is
2 min read
Foundation CSS Pagination Centered
Foundation CSS is an open-source & responsive front-end framework built by ZURB foundation in September 2011, that makes it easy to design beautiful responsive websites, apps, and emails that look amazing & can be accessible to any device. It is used by many companies such as Facebook, eBay, Mozilla, Adobe, and even Disney. The framework is
2 min read
Foundation CSS Pagination
Foundation CSS is the frontend framework of CSS that is used to build responsive websites, apps, and emails that work perfectly on any device. It is written using HTML, CSS, and Javascript and is used by many famous companies like Amazon, Facebook, eBay, etc. It uses packages like Grunt and Libsass for fast coding and controlling and Saas compiler
3 min read
Primer CSS Numbered Pagination
Primer CSS is open-source on Github that is created with GitHub’s design system. We can use Primer CSS by installing it via npm or include the CDN link in our HTML file. It has different types of styles like spacing, color, and typography. Primer CSS Pagination is used to jump to any related page using the link. Primer CSS Numbered Pagination is us
2 min read
Primer CSS Pagination
Primer CSS is a free open-source CSS framework that is built upon systems that create the foundation of the basic style elements such as spacing, typography, and color. This systematic method makes sure our patterns are steady and interoperable with every other. Its approach to CSS is influenced by Object-Oriented CSS principles, functional CSS, an
2 min read
Foundation CSS Pagination Sass Reference
Foundation CSS is an open-source and responsive front-end framework built by ZURB foundation in September 2011, that makes it easy to design beautiful responsive websites, apps, and emails that look amazing and can be accessible to any device. It is used by many companies such as Facebook, eBay, Mozilla, Adobe, and even Disney. The framework is bui
4 min read
How to Add Borders to Pagination in CSS ?
Add borders to Pagination is when you have many pages of content and must move between them. Making these page buttons look better can make navigating easier and more enjoyable for users. One way to do this is by adding borders to the page buttons using CSS. These are the following approaches: Table of ContentUsing Border PropertyUsing Border-Style
3 min read
How to Add Pagination in HTML Table ?
Pagination is a common feature in web applications, especially when dealing with large datasets. It helps in dividing the data into manageable chunks, improving the user experience by reducing the amount of data displayed at once and speeding up page loading times. In this article, we will discuss the approach to add pagination to an HTML table usi
3 min read
How to make table searchable and sortable with pagination using jQuery?
The jQuery fancyTable plugin helps the developers to design HTML tables that are searchable and sortable with pagination feature. This plugin is totally based on JavaScript and HTML. Official website for plugin: Please take care of file paths while implementing the codes. https://github.com/myspace-nu/jquery.fancyTable Example 1: The following code
3 min read
Pagination using Node, Mongo, Express.js and EJS
In this article, we will dive into the process of implementing pagination in our web application using NodeJS, MongoDB, Express, and EJS for dynamic HTML rendering. Additionally, we'll enhance the visual appeal of our pagination controls with CSS. Our focus will be on creating a user profile system where users can create a new profile and scrolling
4 min read
How to make Pagination using Angular UI Bootstrap ?
In this article, we will see how to make Dropdown using Angular UI bootstrap Angular UI Bootstrap is an Angular JS framework created by Angular UI developers for providing better UI which can be used easily. Syntax: <div uib-pagination></div> Download AngularUI from the link: https://angular-ui.github.io/bootstrap Approach: First, add A
1 min read
How to implement pagination in React using Hooks?
Implementing pagination in React using hooks involves managing the state of the current page and the number of items per page, as well as rendering the paginated data accordingly. Implementing pagination in React using Hooks:Setup Initial State: Use the useState hook to manage the state for the current page and items per page.import React,{ useStat
3 min read
How to do Pagination in Node.js using Sorting Ids ?
Implementing pagination in a Node.js application involves fetching and displaying data in chunks or pages, typically from a database. One common approach to pagination is using sorting IDs, where each record in the dataset is assigned a unique identifier (ID) that determines its position in the sorted sequence. This method allows you to efficiently
4 min read
Pagination Component using React Hooks
Pagination on websites refers to the way of displaying a large set of data in smaller chunks. In React, it's super easy to create a pagination component with the help of the `useEffect` and `useState` hooks. we will create a pagination component using React hooks. Output Preview: Let us have a look at how the final output will look like. Prerequisi
3 min read
Pagination using Datatables
DataTables are a modern jQuery plugin for adding interactive and advanced controls to HTML tables for the webpage. In this article, we will learn to implement pagination using DataTables. Other features include sorting and multiple column ordering. The pre-compiled files which are needed to implement codes are CSS: <link rel="stylesheet" href="h
3 min read
How to add Pagination in Nextjs using Algolia ?
Adding pagination to a Next.js application with Algolia involves fetching and displaying paginated search results from Algolia’s API. This setup provides an efficient way to handle large datasets by loading data in chunks. In this article, we will learn How we can add pagination in the NextJS project using Algolia. ApproachTo add our search feature
2 min read
Create a Product Review and Rating System Using HTML CSS and JavaScript
Creating a product review and rating system using HTML, CSS, and JavaScript involves several steps. In this article, we will create a Product Review and Rating System using HTML, CSS, and JavaScript. Approach:Create the HTML structure for your product review and rating system. You'll need sections for product information, user reviews, and a form f
3 min read