JavaScript JSON Array Pagination

JavaScript JSON Array Pagination
Code Snippet:Vanilla JS pagination
Author: xavier maimo
Published: January 14, 2024
Last Updated: January 22, 2024
Downloads: 1,201
License: MIT
Edit Code online: View on CodePen
Read More

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 chiholiu10@gmail.com

(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.

Leave a Comment

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

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

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

X