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 JSON Array Pagination

JavaScript JSON Array Pagination

January 22, 2024January 14, 2024 by Asif Mughal
JavaScript JSON Array Pagination
Share This:
Code Snippet:Vanilla JS pagination
Author: xavier maimo
Published: January 14, 2024
Last Updated: January 22, 2024
Downloads: 2,060
License: MIT
Edit Code online: View on CodePen
Read More
 Demo
Download (File path is not allowed!)

This JavaScript code snippet helps you to create a pagination system for a JSON array. It allows you to navigate through the JSON data, displaying a limited number of records per page. You can easily switch between pages using “Prev” and “Next” buttons or by clicking on specific page numbers.

This code enhances the user experience when dealing with large datasets by breaking them into manageable sections. You can use this code in web applications and websites with large datasets. It simplifies the process of displaying and managing paginated JSON arrays.

How to Create Javascript JSON Array Pagination

1. First, include the HTML structure provided in the code snippet within your HTML file. This structure includes pagination buttons, a container for your data, and page number indicators.

<div class="pagination">
  <div class="tableList" id="listingTable"></div>
  <div class="pagination-block">
    <span class="pageButton outline-none" id="button_prev">Prev</span>
    <span id="page_number" class="outline-none"></span>
    <span class="pageButton outline-none" id="button_next">Next</span>
  </div>
</div>

2. Use the following CSS code to style the pagination interface. Feel free to customize it to match your website’s design.

body {
  margin: 0;
  padding: 0;
  width: 100%;
  overflow-x: hidden;
  font-family: Arial;
  background-color: #888;
}
.pagination {
  max-width: 400px;
  min-width: 300px;
  width: 100%;
  display: block;
  margin: 0 auto;
  position: relative;
  background-color: lightgreen;
  padding: 20px;
}
.pagination .tableList {
  min-height: 250px;
  text-indent: 20px;
}
 .tableList .objectBlock {
  position: relative;
  background-color: black;
  color: white;
  padding: 10px;
  margin-bottom: 10px;
}
 .pageButton {
  border: 1px solid black;
  padding: 5px;
}
 .clickPageNumber {
  background-color: lightgrey;
  padding: 5px;
  margin-left: 2px;
  margin-right: 2px;
}
 .pagination-block {
  text-align: center;
  width: 100%;
}
 .pagination-block span {
  display: inline-block;
}
.pagination-block .pageButton {
  background-color: grey;
  color: white;
}
 .pagination-block span:hover {
  cursor: pointer;
}
 .opacity {
  opacity: 0.5;
}
 .outline-none {
  outline: none;
  -webkit-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
          user-select: none;
}

3. Finally, copy the following JavaScript code into a separate JavaScript file or within a <script> tag in your HTML file.

// if you have any suggestion of questions, pleasse feel free to send me an email to [email protected]

(function() {
    "use strict";

    function Pagination() {
      
       const objJson = [
          { adName: "adName 1"},
          { adName: "adName 2"},
          { adName: "adName 3"},
          { adName: "adName 4"},
          { adName: "adName 5"},
          { adName: "adName 6"},
          { adName: "adName 7"},
          { adName: "adName 8"},
          { adName: "adName 9"},
          { adName: "adName 10"},
          { adName: "adName 11"},
          { adName: "adName 12"},
          { adName: "adName 13"},
          { adName: "adName 14"},
          { adName: "adName 15"},
          { adName: "adName 16"}
      ];

      const prevButton = document.getElementById('button_prev');
      const nextButton = document.getElementById('button_next');
      const clickPageNumber = document.querySelectorAll('.clickPageNumber');
      
      let current_page = 1;
      let records_per_page = 5;
      
      this.init = function() {
          changePage(1);
          pageNumbers();
          selectedPage();
          clickPage();
          addEventListeners();
     }
      
      let addEventListeners = function() {
          prevButton.addEventListener('click', prevPage);
          nextButton.addEventListener('click', nextPage);   
      }
            
      let selectedPage = function() {
          let page_number = document.getElementById('page_number').getElementsByClassName('clickPageNumber'); 
          for (let i = 0; i < page_number.length; i++) {
              if (i == current_page - 1) {
                  page_number[i].style.opacity = "1.0";
              } 
              else {
                  page_number[i].style.opacity = "0.5";
              }
          }   
      }  
      
      let checkButtonOpacity = function() {
        current_page == 1 ? prevButton.classList.add('opacity') : prevButton.classList.remove('opacity');
        current_page == numPages() ? nextButton.classList.add('opacity') : nextButton.classList.remove('opacity');
      }

      let changePage = function(page) {
          const listingTable = document.getElementById('listingTable');

          if (page < 1) {
              page = 1;
          } 
          if (page > (numPages() -1)) {
              page = numPages();
          }
       
          listingTable.innerHTML = "";

          for(var i = (page -1) * records_per_page; i < (page * records_per_page) && i < objJson.length; i++) {
              listingTable.innerHTML += "<div class='objectBlock'>" + objJson[i].adName + "</div>";
          }
          checkButtonOpacity();
          selectedPage();
      }

      let prevPage = function() {
          if(current_page > 1) {
              current_page--;
              changePage(current_page);
          }
      }

      let nextPage = function() {
          if(current_page < numPages()) {
              current_page++;
              changePage(current_page);
          } 
      }

      let clickPage = function() {
          document.addEventListener('click', function(e) {
              if(e.target.nodeName == "SPAN" && e.target.classList.contains("clickPageNumber")) {
                  current_page = e.target.textContent;
                  changePage(current_page);
              }
          });
      }

      let pageNumbers = function() {
          let pageNumber = document.getElementById('page_number');
              pageNumber.innerHTML = "";

          for(let i = 1; i < numPages() + 1; i++) {
              pageNumber.innerHTML += "<span class='clickPageNumber'>" + i + "</span>";
          }
      }

      let numPages = function() {
          return Math.ceil(objJson.length / records_per_page);  
      }
   }
  let pagination = new Pagination();
  pagination.init();
})();

Modify the objJson variable to contain your JSON data. Each object represents a record to be displayed. You can change the number of records displayed per page by modifying the records_per_page variable. By default, it’s set to 5.

That’s all! hopefully, you have successfully created JSON Array Pagination using JavaScript. If you have any questions or suggestions, feel free to comment below.

Similar Code Snippets:

  • JavaScript Change CSS Variable Root

    JavaScript Change CSS Variable Root

  • Calorie Calculator Source Code

    Calorie Calculator Source Code

  • Sliding Puzzle Game in JavaScript

    Sliding Puzzle Game in JavaScript

  • Credit Cart Checkout Form in Vanilla JavaScript

    Credit Cart Checkout Form in Vanilla JavaScript

  • Todo List in JavaScript with Search Box

    Todo List in JavaScript with Search Box

  • JavaScript Color Wheel Picker

    JavaScript Color Wheel Picker

  • Automatic Animated Image Slider in JavaScript

    Automatic Animated Image Slider in JavaScript

  • JavaScript Audio Waveform Visualizer

    JavaScript Audio Waveform Visualizer

  • JavaScript Unit Converter Source Code

    JavaScript Unit Converter Source Code

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
Bootstrap 5 Toast Dynamic Message
JavaScript Parallax Tilt Effect Cards on Hover

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,411 views
  • 25+ Best JavaScript Shopping Cart Examples with Demo - 211,942 views
  • Bootstrap Multiselect Dropdown with Checkboxes - 150,950 views
  • Bootstrap 5 Buttons with Icon and Text Tutorial & Demo - 112,363 views
  • 19+ Bootstrap Select Dropdown with Search Box Tutorial & Examples - 101,047 views
  • Bootstrap 5 Sidebar Menu with Submenu Collapse/Hover Tutorial Demo - 88,106 views
  • 99+ Social Media Buttons HTML Code Sample & Tutorial - 86,393 views
  • 19+ Bootstrap 5 Mega Menu Responsive/Drop Down Examples - 86,392 views
  • Bootstrap 4 Modal Popup Login Form Tutorial & Demo - 82,150 views
  • Bootstrap Vertical Menu with Submenu on Click - 80,202 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