Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
           CodeHim.com

Free Web Design Code & Scripts

       
  • Home
  • Code Snippets
    • Accordion
    • Creative
    • Carousel
    • Date & Time
    • Gallery
    • LightBox
    • Menu & Nav
    • Modal
    • Others
    • Portfolio
    • Social Media
    • Text & Input
    • Video Player
    • Zoom
  • HTML & CSS
  • Bootstrap
  • JavaScript
  • Collections
  • About
  • Contact
  • Buy Me a Coffee

Home / Vanilla JavaScript / JavaScript Pagination for List Items

JavaScript Pagination for List Items

January 22, 2024January 21, 2024 by Asif Mughal
JavaScript Pagination for List Items
Share This:
Code Snippet:Pagination with Vanilla JavaScript
Author: Envato Tuts+
Published: January 21, 2024
Last Updated: January 22, 2024
Downloads: 2,780
License: MIT
Edit Code online: View on CodePen
Read More
 Demo
Download (File path is not allowed!)

This JavaScript Pagination for List Items code allows you to split a long list into multiple pages. It works by displaying a limited number of list items at a time and provides navigation buttons to move between pages. This code helps you organize and present lengthy lists more effectively.

You can use this code on websites with extensive lists of items, such as product catalogs or articles, to improve user experience. Moreover, it benefits users by breaking down long lists into manageable pages, making navigation easier.

How to Create Javascript Pagination For List Items

1. In your HTML file, create a list (ul) with the id "paginated-list". This is the list you want to paginate. The list items (li) inside it represent the items you want to split into pages.

<main>

  <h1>Pagination with Vanilla JavaScript</h1>
  <ul id="paginated-list" data-current-page="1" aria-live="polite">
    <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>
    <li>Item 11</li>
    <li>Item 12</li>
    <li>Item 13</li>
    <li>Item 14</li>
    <li>Item 15</li>
    <li>Item 16</li>
    <li>Item 17</li>
    <li>Item 18</li>
    <li>Item 19</li>
    <li>Item 20</li>
    <li>Item 21</li>
    <li>Item 22</li>
    <li>Item 23</li>
    <li>Item 24</li>
    <li>Item 25</li>
    <li>Item 26</li>
    <li>Item 27</li>
    <li>Item 28</li>
    <li>Item 29</li>
    <li>Item 30</li>
    <li>Item 31</li>
    <li>Item 32</li>
    <li>Item 33</li>
    <li>Item 34</li>
    <li>Item 35</li>
    <li>Item 36</li>
    <li>Item 37</li>
    <li>Item 38</li>
    <li>Item 39</li>
    <li>Item 40</li>
    <li>Item 41</li>
    <li>Item 42</li>
    <li>Item 43</li>
    <li>Item 44</li>
    <li>Item 45</li>
    <li>Item 46</li>
    <li>Item 47</li>
    <li>Item 48</li>
    <li>Item 49</li>
    <li>Item 50</li>
  </ul>

  <nav class="pagination-container">
    <button class="pagination-button" id="prev-button" aria-label="Previous page" title="Previous page">
      &lt;
    </button>

    <div id="pagination-numbers">

    </div>

    <button class="pagination-button" id="next-button" aria-label="Next page" title="Next page">
      &gt;
    </button>
  </nav>
</main>

2. Now, ensure that the following CSS code is included in your stylesheet or HTML file to style the pagination elements.

@import url('https://fonts.googleapis.com/css2?family=Inter&display=swap');

body {
  font-family: 'Inter', sans-serif;
  line-height: 1.7;
  font-size: 1.1rem;
  margin: 0;
  color: #27253d;
  background: #e6f3f8;
}

main {
  position: relative;
  padding: 1rem 1rem 3rem;
  min-height: calc(100vh - 4rem);
}

h1 {
  margin-top: 0;
}

.hidden {
  display: none;
}

.pagination-container {
  width: calc(100% - 2rem);
  display: flex;
  align-items: center;
  position: absolute;
  bottom: 0;
  padding: 1rem 0;
  justify-content: center;
}

.pagination-number,
.pagination-button{
  font-size: 1.1rem;
  background-color: transparent;
  border: none;
  margin: 0.25rem 0.25rem;
  cursor: pointer;
  height: 2.5rem;
  width: 2.5rem;
  border-radius: .2rem;
}

.pagination-number:hover,
.pagination-button:not(.disabled):hover {
  background: #fff;
}

.pagination-number.active {
  color: #fff;
  background: #0085b6;
}

footer {
  padding: 1em;
  text-align: center;
  background-color: #FFDFB9;
}

footer a {
  color: inherit;
  text-decoration: none;
}

footer .heart {
  color: #DC143C;
}

3. Finally, include the JavaScript code in your HTML file or link it externally, and make sure it’s placed after the HTML elements you want to paginate.

const paginationNumbers = document.getElementById("pagination-numbers");
const paginatedList = document.getElementById("paginated-list");
const listItems = paginatedList.querySelectorAll("li");
const nextButton = document.getElementById("next-button");
const prevButton = document.getElementById("prev-button");

const paginationLimit = 10;
const pageCount = Math.ceil(listItems.length / paginationLimit);
let currentPage = 1;

const disableButton = (button) => {
  button.classList.add("disabled");
  button.setAttribute("disabled", true);
};

const enableButton = (button) => {
  button.classList.remove("disabled");
  button.removeAttribute("disabled");
};

const handlePageButtonsStatus = () => {
  if (currentPage === 1) {
    disableButton(prevButton);
  } else {
    enableButton(prevButton);
  }

  if (pageCount === currentPage) {
    disableButton(nextButton);
  } else {
    enableButton(nextButton);
  }
};

const handleActivePageNumber = () => {
  document.querySelectorAll(".pagination-number").forEach((button) => {
    button.classList.remove("active");
    const pageIndex = Number(button.getAttribute("page-index"));
    if (pageIndex == currentPage) {
      button.classList.add("active");
    }
  });
};

const appendPageNumber = (index) => {
  const pageNumber = document.createElement("button");
  pageNumber.className = "pagination-number";
  pageNumber.innerHTML = index;
  pageNumber.setAttribute("page-index", index);
  pageNumber.setAttribute("aria-label", "Page " + index);

  paginationNumbers.appendChild(pageNumber);
};

const getPaginationNumbers = () => {
  for (let i = 1; i <= pageCount; i++) {
    appendPageNumber(i);
  }
};

const setCurrentPage = (pageNum) => {
  currentPage = pageNum;

  handleActivePageNumber();
  handlePageButtonsStatus();
  
  const prevRange = (pageNum - 1) * paginationLimit;
  const currRange = pageNum * paginationLimit;

  listItems.forEach((item, index) => {
    item.classList.add("hidden");
    if (index >= prevRange && index < currRange) {
      item.classList.remove("hidden");
    }
  });
};

window.addEventListener("load", () => {
  getPaginationNumbers();
  setCurrentPage(1);

  prevButton.addEventListener("click", () => {
    setCurrentPage(currentPage - 1);
  });

  nextButton.addEventListener("click", () => {
    setCurrentPage(currentPage + 1);
  });

  document.querySelectorAll(".pagination-number").forEach((button) => {
    const pageIndex = Number(button.getAttribute("page-index"));

    if (pageIndex) {
      button.addEventListener("click", () => {
        setCurrentPage(pageIndex);
      });
    }
  });
});

You can customize the paginationLimit variable to control the number of items displayed on each page. By default, it’s set to 10.

That’s it! hopefully, you’ve now successfully added pagination to your list. Users can browse through your long list of items with ease. If you have any questions or suggestions, feel free to comment below.

Similar Code Snippets:

  • Simple Parallax Effect in Vanilla JavaScript

    Simple Parallax Effect in Vanilla JavaScript

  • JavaScript Random Number Generator Between Range

    JavaScript Random Number Generator Between Range

  • Bootstrap 4 Modern Pagination with jQuery

    Bootstrap 4 Modern Pagination with jQuery

  • Water Intake Calculator in JavaScript

    Water Intake Calculator in JavaScript

  • Zoom Image on Mouseover using JavaScript

    Zoom Image on Mouseover using JavaScript

  • Calorie Calculator Source Code

    Calorie Calculator Source Code

  • Custom Scrollbar for all Browsers with JavaScript CSS

    Custom Scrollbar for all Browsers with JavaScript CSS

  • Product Recommendation Based On Selection in JavaScript

    Product Recommendation Based On Selection in JavaScript

  • JavaScript Get Browser Name and Version

    JavaScript Get Browser Name and Version

Asif Mughal

I code and create web elements for amazing people around the world. I like work with new people. New people new Experiences.
I truly enjoy what I’m doing, which makes me more passionate about web development and coding. I am always ready to do challenging tasks whether it is about creating a custom CMS from scratch or customizing an existing system.

Categories Vanilla JavaScript Tags Pagination
Breakout Game with Vanilla JavaScript
Mask Image and Text Using CSS Clip Path and SVG

Leave a Comment Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  • Categories

    • Accordion 22
    • Bootstrap 81
      • Bootstrap Accordion 1
      • Bootstrap Buttons 4
      • Bootstrap Cards 2
      • Bootstrap Carousel 2
      • Bootstrap Dropdowns 2
      • Bootstrap Forms 6
      • Bootstrap Jumbotron 1
      • Bootstrap Modals 2
      • Bootstrap Navbars 6
      • Bootstrap Panels 1
      • Bootstrap Progress Bars 1
      • Bootstrap Text & Input 3
    • Carousel 58
    • Chart & Graph 15
    • Date & Time 49
    • Gallery 39
    • HTML5 & CSS3 201
    • Layout 17
    • LightBox 19
    • Menu & Nav 95
    • Modal 18
    • Others 58
    • Portfolio 8
    • Social Media 10
    • Text & Input 120
    • Vanilla JavaScript 163
    • Zoom 12

You May Like

Alert (7) Analog Clock (4) Analog Clocks (5) Back to Top (4) Calculator (16) Calendar (5) Chart (3) Color Picker (4) Contact Us Forms (5) Countdown Timer (6) Datepicker (9) Digital Clocks (10) Drag and Drop (4) Dropdown Menu (23) File Uploader (4) Hamburger Menu (9) Horizontal Menu (24) Hover Effects (5) HTML5 Canvas (8) Image Sliders (40) Mega Menu (11) Modal (5) Multi-Level Menu (9) News Ticker (4) Notification (9) Off-Canvas Menu (10) Pagination (5) Parallax (8) Popup Lightbox (20) Progress Bar (5) Range Sliders (4) Scrolling Effects (28) Search Box (4) Select Dropdown (4) Shopping Cart (3) Side Menu (16) Slideshow (19) Social Share Buttons (3) Tabs (9) Text (11) Timeline (5) Timer (4) Tooltip (4) Typing Effect (6) Vertical Menu (14)

Latest Code Snippets

  • Common Open Source Security Vulnerabilities and How to Mitigate ThemCommon Open Source Security Vulnerabilities and How to Mitigate Them
    October 12, 2024
  • Animating Grid-column on Hover Using CSSAnimating Grid-column on Hover Using CSS
    April 1, 2024
  • Star Trails Animation On Mousemove in JavaScriptStar Trails Animation On Mousemove in JavaScript
    March 31, 2024
  • Gravity Button Using Pure CSSGravity Button Using Pure CSS
    March 31, 2024
  • Padlock Toggle Switch in CSSPadlock Toggle Switch in CSS
    March 31, 2024
  • Scroll-driven Animations in Pure CSSScroll-driven Animations in Pure CSS
    March 31, 2024
  • Interactive Notification Center UI in Vanilla JSInteractive Notification Center UI in Vanilla JS
    March 31, 2024
  • Emoji Spinner in Vanilla JavaScriptEmoji Spinner in Vanilla JavaScript
    March 31, 2024
  • Reveal Secret Code Using CSSReveal Secret Code Using CSS
    March 31, 2024
  • Toggle Button in CSS With Stretchable Elastic EffectToggle Button in CSS With Stretchable Elastic Effect
    March 31, 2024

Popular

  • 65+ Login Page in HTML with CSS Code Sample Simple to Difficult - 947,396 views
  • 25+ Best JavaScript Shopping Cart Examples with Demo - 211,933 views
  • Bootstrap Multiselect Dropdown with Checkboxes - 150,948 views
  • Bootstrap 5 Buttons with Icon and Text Tutorial & Demo - 112,357 views
  • 19+ Bootstrap Select Dropdown with Search Box Tutorial & Examples - 101,034 views
  • Bootstrap 5 Sidebar Menu with Submenu Collapse/Hover Tutorial Demo - 88,103 views
  • 99+ Social Media Buttons HTML Code Sample & Tutorial - 86,392 views
  • 19+ Bootstrap 5 Mega Menu Responsive/Drop Down Examples - 86,388 views
  • Bootstrap 4 Modal Popup Login Form Tutorial & Demo - 82,145 views
  • Bootstrap Vertical Menu with Submenu on Click - 80,199 views

Advertisement

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

CodeHim
  • About
  • Contact Us
  • Terms and Conditions
  • Privacy Policy
Top Categories
  • Bootstrap Snippets
  • JavaScript Snippets
  • HTML CSS Snippets
  • Menu & Nav Snippets
Get in Touch

Follow us on social media to be updated with latest web design code & scripts...

All Rights Reserved © 2026 - CodeHim Inc

Please Rel0ad/PressF5 this page if you can't click the download/preview link

F5
X