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!
TABLE OF CONTENTS
JAVASCRIPT PAGINATION DEMO
For you guys who just want to use this as a “plugin”, here’s a “quickstart guide” (download link is below).
PAGINATION WITH URL STRING
<!-- (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>
- Load the CSS and Javascript.
- Create a
<div>
to generate the pagination in. - 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
<!-- (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
If you want to do some “deep customization”, here’s the pagination script in more detail.
THE JAVASCRIPT
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("⟪", 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("⟫", 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:
- Initialize and set the “default options” if not provided.
- 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. - Add a
class="paginate"
to the target container. - Lastly, generate the HTML pagination squares themselves… 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 { 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, and fit the theme of your own project.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA 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.
ADDING SEARCH PARAMETERS
If you want to add search parameters to the pagination, simply append it to the end of the URL.
// URL STRING
paginator({
target : document.getElementById("ID"),
total : 10,
click : "1-url-string.html?search=ABC"
});
// FETCH GET
function load (pg) {
fetch ("http://site.com/?search=ABC&pg="+pg)
// ...
}
HOW TO CALCULATE PAGINATION!?
As you can see, you only pass in the current and total number of pages into the “pagination plugin”. You have to work out the calculations yourself, as it’s different for everybody – Some may fetch database entries, some work with an array/object, and some may read from a CSV/Excel file. I can only give general calculation examples here:
- Get the total number of entries.
- Database –
SELECT COUNT(*) FROM `table`
- An array –
ARRAY.length
- An object –
Object.keys(OBJECT).length
- Database –
- Get the entries for the current page.
START = (PAGE NOW - 1) * ENTRIES PER PAGE
- Database –
SELECT * FROM `table` LIMIT START, ENTRIES PER PAGE
- Array – Extract from
START
toSTART + ENTRIES PER PAGE
LINKS & REFERENCES
- Simple Pagination Using PHP MySQL – Code Boxx
- Example on CodePen – Simple HTML JS Pagination
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!
hi, i have read and copy your code. it is great!
but how to put the value??
you didn’t mention how to do so.
If you mean “search query”, see “ADDING SEARCH PARAMETERS” above.
https://code-boxx.com/simple-ajax-php/