Free Web Design Code & Scripts

JavaScript JSON Array Pagination

Javascript Json Array Pagination
Code Snippet:Vanilla JS pagination
Author: xavier maimo
Published: 5 months ago
Last Updated: 5 months ago
Downloads: 163
License: MIT
Edit Code online: View on CodePen
Read More

This tutorial provides a step-by-step guide on how to implement Javascript Json Array Pagination. Pagination is a crucial feature for displaying large datasets in a user-friendly manner, and this guide will show you how to create a simple yet effective pagination system for a JSON array. This approach can significantly improve the user experience by breaking down content into manageable chunks, making it easier to navigate and find specific information.

Setting Up the HTML Structure

First, you need to create the basic HTML structure for the pagination component. This includes a container for the list of items, as well as elements for the pagination controls (previous, next, and page number buttons).

<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>
    <script  src="./script.js"></script>

Applying CSS Styles

Next, we’ll add CSS to style the pagination elements and make them visually appealing. These styles will control the layout, colors, and appearance of the pagination controls and list items.

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

Implementing the JavaScript Logic

The core of the pagination functionality lies in the JavaScript code. This code will handle the JSON data, calculate the number of pages, display the correct subset of data for each page, and manage the navigation between pages.

// 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();
})();

Conclusion

By following these steps, you should now have a working implementation of Javascript Json Array Pagination. This technique is essential for managing and displaying large datasets efficiently, enhancing user experience, and improving website performance.

Loading... ...

Loading preview...

Device: Desktop
Dimensions: 1200x800
Lines: 0 Characters: 0 Ln 1, Ch 1

Leave a Comment

About W3Frontend

W3Frontend provides free, open-source web design code and scripts to help developers and designers build faster. Every snippet is reviewed before publishing for quality. Learn more.