Core JavaScript

Pagination with Next and Previous

This JavaScript program shows how to perform pagination with JavaScript.

PaginationFPNL.html

<!DOCTYPE html>
<html>
  <head>
    <title>XoaX.net's JavaScript</title>
     <script type="text/javascript"  src="PaginationFPNL.js">
     </script>
  </head>
  <body onload="Initialize()">
    <div style="text-align:center;">
      <input type="button" id="idFirst" onclick="First()" value="First" />
      <input type="button" id="idPrev" onclick="Previous()" value="Previous" />
      <input type="button" id="idNext" onclick="Next()" value="Next" />
      <input type="button" id="idLast" onclick="Last()" value="Last" />
      <div id="idPage"></div>
    </div>
  </body>
</html>

PaginationFPNL.js

var iaItemList = null;
var iaPageList = new Array();
var iCurrPage = 1;
var iItemsPerPage = 12;
var iItemsPerLine = 3;
var iPageCount = 0;

function Initialize() {
  iaItemList = new Array();
  for (iItem = 1; iItem <= 200; ++iItem) {
    iaItemList.push(iItem);
  }
  iPageCount = Math.ceil(iaItemList.length / iItemsPerPage);
  FillPage();
}
function FillPage() {
  // Fill the page list with items
  var iFirstItem = ((iCurrPage - 1) * iItemsPerPage);
  var iLastItem = iFirstItem + iItemsPerPage;
  iaPageList = iaItemList.slice(iFirstItem, iLastItem);
  // Render the items on the page
  document.getElementById("idPage").innerHTML = "<br/>";
  for (iItem = 0; iItem < iaPageList.length; ++iItem) {
    document.getElementById("idPage").innerHTML += iaPageList[iItem] + " ";
    // Add a br to end each line and one to put in a space.
    if ((iItem % iItemsPerLine) == (iItemsPerLine - 1)) {
      document.getElementById("idPage").innerHTML += "<br/><br/>";
    }
  }
  // Disable all unusable buttons
  document.getElementById("idFirst").disabled = (iCurrPage == 1);
  document.getElementById("idPrev").disabled = (iCurrPage == 1);
  document.getElementById("idNext").disabled = (iCurrPage == iPageCount);
  document.getElementById("idLast").disabled = (iCurrPage == iPageCount);
}

function First() {
  iCurrPage = 1;
  FillPage();
}
function Previous() {
  iCurrPage = ((iCurrPage <= 1) ? 1 : (iCurrPage - 1));
  FillPage();
}
function Next() {
  iCurrPage = ((iCurrPage >= iPageCount) ? iPageCount : (iCurrPage + 1));
  FillPage();
}
function Last() {
  iCurrPage = iPageCount;
  FillPage();
}
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.