Simple Pagination With Javascript HTML (Free Download)

Welcome to a tutorial on how to create simple pagination with pure Javascript and HTML. Have a huge array of data that needs to be displayed in an HTML table and paginated? Or maybe split a long article into multiple pages? Well, here is a quick sharing of a pagination script that I made, and the logic behind it – Read on!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TABLE OF CONTENTS

Download & Demo How It Works Useful Bits & Links
The End

 

DOWNLOAD & DEMO

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICKSTART & DEMO

PAGINATION WITH URL STRING

1-url-string.html
<!-- (A) LOAD CSS + JS -->
<link rel="stylesheet" href="paginate.css"/>
<script src="paginate.js"></script>
 
<!-- (B) HTML CONTAINER -->
<div id="demoA"></div>
 
<!-- (C) INIT PAGINATION -->
<script>
paginator({
  target : document.getElementById("demoA"),
  total : 10,
  click : "1-url-string.html"
});
</script>

For you guys who just want to use this as a “plugin”:

  1. Load the CSS and Javascript. Doh.
  2. Create a <div> to generate the pagination in.
  3. Call paginator() to create the pagination.
    • target Self-explanatory. The target <div> to generate pagination.
    • total The total number of pages.
    • click Target URL for the pagination.

That’s all. The pagination squares will point to your specified URL with a pg=N parameter attached behind.

 

 

PAGINATION WITH JAVASCRIPT FUNCTION

2-js-function.html
<!-- (A) LOAD PAGINATE CSS + JS -->
<link rel="stylesheet" href="paginate.css"/>
<script src="paginate.js"></script> 
 
<!-- (B) HTML CONTAINER -->
<div id="demoB"></div>
 
<!-- (C) JAVASCRIPT -->
<script>
// (C1) YOUR JS FUNCTION TO HANDLE PAGINATION
function load (pg) {
  /* (C1-1) AJAX FETCH PAGE
  fetch ("http://site.com/?pg="+pg)
  .then(res => res.text())
  .then((txt) => {
    document.getElementById("WRAP").innerHTML = txt;
  }); */
 
  // (C1-2) REDRAW PAGINATION
  paginator({
    target : document.getElementById("demoB"),
    total : 10,
    current : pg,
    click : load
  });
}
 
// (C2) INIT PAGINATION
load(1);
</script>

For you guys who prefer to use AJAX for loading, or want to use Javascript to handle the pagination:

  • (C) Create your own Javascript function – It must accept a page pg parameter.
  • (C1) AJAX load, get form data, do whatever processing is required.
  • (C2) Once again, use paginator() to help draw/update the HTML pagination.

 

 

HOW IT WORKS

For you guys who want to do some “deep customization”, here’s the pagination script in more detail.

 

THE JAVASCRIPT

paginate.js
function paginator (instance) {
// target : html element to generate pagination.
// total : total number of pages.
// click : url string or function to call on click.
// current : (optional) current page, default 1.
// adj : (optional) num of adjacent pages beside "current page", default 2.
 
  // (A) INIT & SET DEFAULTS
  if (instance.current === undefined) {
    let param = new URLSearchParams(window.location.search);
    instance.current = param.has("pg") ? Number.parseInt(param.get("pg")) : 1;
  }
  if (instance.adj === undefined) { instance.adj = 2; }
  if (instance.adj <= 0) { instance.adj = 1; }
  if (instance.current <= 0) { instance.current = 1; }
  if (instance.current > instance.total) { instance.current = instance.total; }

  // (B) URL STRING ONLY - DEAL WITH QUERY STRING & APPEND PG=N
  const jsmode = typeof instance.click == "function";
  if (jsmode == false) {
    if (instance.click.indexOf("?") == -1) { instance.click += "?pg="; }
    else { instance.click += "&pg="; }
  }
 
  // (C) HTML PAGINATION WRAPPER
  instance.target.innerHTML = "";
  instance.target.classList.add("paginate");
 
  // (D) DRAW PAGINATION SQUARES
  // (D1) HELPER FUNCTION TO DRAW PAGINATION SQUARE
  const square = (txt, pg, css) => {
    let el = document.createElement("a");
    el.innerHTML = txt;
    if (css) { el.className = css; }
    if (jsmode) { el.onclick = () => { instance.click(pg); }; }
    else { el.href = instance.click + pg; }
    instance.target.appendChild(el);
  };

  // (D2) BACK TO FIRST PAGE (DRAW ONLY IF SUFFICIENT SQUARES)
  if (instance.current - instance.adj > 1) { square("&#10218;", 1, "first"); }

  // (D3) ADJACENT SQUARES BEFORE CURRENT PAGE
  let temp;
  if (instance.current > 1) {
    temp = instance.current - instance.adj;
    if (temp<=0) { temp = 1; }
    for (let i=temp; i<instance.current; i++) { square(i, i); }
  }
 
  // (D4) CURRENT PAGE
  square(instance.current, instance.current, "current");

   // (D5) ADJACENT SQUARES AFTER CURRENT PAGE
  if (instance.current < instance.total) {
    temp = instance.current + instance.adj;
    if (temp > instance.total) { temp = instance.total; }
    for (let i=instance.current+1; i<=temp; i++) { square(i, i); }
  }
 
  // (D6) SKIP TO LAST PAGE (DRAW ONLY IF SUFFICIENT SQUARES)
  if (instance.current <= instance.total - instance.adj - 1) {
    square("&#10219;", instance.total, "last");
  }
}

Look no further, there is only a single paginator() in this script – You already know what it does, generate the HTML pagination. This looks intimidating at first, but it is less than 70 lines of code:

  1. Initialize and set the “default options” if not provided.
  2. If it is a “URL string pagination”, we deal with the query string. In particular, we need to append a ?pg=N behind the URL.
  3. Add a class="paginate" to the target container.
  4. Lastly, generate the pagination squares itself… Not going to explain this step-by-step, read through the code if you want.

 

 

THE CSS

The Javascript will generate pagination HTML like this:

<div id="demo" class="paginate">
  <a class="first" href="page.html?pg=1">⟪</a>
  <a href="page.html?pg=3">3</a>
  <a class="current" href="page.html?pg=4">4</a>
  <a href="page.html?pg=5">5</a>
  <a class="last" href="page.html?pg=10">⟫</a>
</div>

So some simple CSS cosmetics for the pagination squares:

paginate.css
paginate { display: flex; }
.paginate a {
  color: #000;
  background: #f2f2f2;
  padding: 8px 10px;
  margin: 2px;
  text-decoration: none;
  cursor: pointer;
}
.paginate a.current {
  color: #fff;
  background: #4486ff;
}
.paginate a:hover {
  color: #000;
  background: #ffe9e9;
}

That’s all. Feel free to style however you want, fit the theme of your own project.

 

 

USEFUL BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published.