This JavaScript code snippet simplifies the implementation of dynamic pagination in web applications. It comes with default settings for items per page, truncation, and visual elements like previous and next buttons, making it adaptable to various project requirements.
The core functionality resides in the Pager
class, which simplifies navigation between pages. It handles user interactions, rendering, and dynamic page additions or removals. Additionally, the code supports event handling, allowing developers to respond to essential events such as initialization, rendering, and page changes.
One user-friendly feature is the ability to choose different visual styles or “skins” for the pagination controls. With this option, developers can easily switch between styles, like Bootstrap or custom icons, to maintain a consistent look and feel across their web applications.
How to Create Dynamic Pagination In Javascript
1. First of all, load the Bootstrap CSS, Material Design Icons, and Google Fonts by adding the following CDN links to the head tag of your HTML document.
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta/css/bootstrap.min.css'> <link rel='stylesheet' href='//cdn.materialdesignicons.com/1.7.22/css/materialdesignicons.min.css'> <link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700'> <link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Roboto:400,500'>
2. Create the HTML structure for pagination as follows. The key element for implementing pagination is the <div id="pager"></div>
element within the <div id="container"></div>
. This is where the pagination control will be generated and displayed on your web page.
<main> <div class="container"> <div class="row"> <div class="col-sm-12"> <h2>Dynamic Pagination</h2> <div id="container"> <div id="pager"></div> <div class="text-muted" id="info"></div> </div> </div> </div> </div> </main>
3. Use the following CSS to style the pagination. You can modify the CSS rules to customize the page buttons according to your needs.
body { margin: 0; font-family: "Roboto Condensed"; font-weight: 400; font-size: 16px; color: #666; } main { margin-top: 10vh; } h2, small, .btn { font-weight: 700; } a, a:hover { color: #0077db; } label { font-weight: 400; } #container { margin: 20px 0; } #pager { margin-bottom: 20px; } #pager::after { display: table; clear: both; content: ""; } .form-control { width: 150px; margin-right: 20px; } .pg-pager { margin: 0; padding: 0; } .pg-pager::after { display: table; clear: both; content: ""; } .pg-pager .pg-item { list-style: outside none; float: left; } .pg-pager .pg-item .pg-link, .pg-pager .pg-item.pg-ellipsis > span { display: block; min-width: 45px; text-align: center; font-weight: 700; text-decoration: none; padding: 6px 12px; color: inherit; border: 1px solid #ccc; margin-left: -1px; } .pg-pager .pg-item .pg-link:hover, .pg-pager .pg-item.pg-ellipsis > span:hover { color: inherit; border-color: #ccc; background-color: #ccc; } .pg-pager .pg-item.pg-active > a, .pg-pager .pg-item.pg-active > a:focus, .pg-pager .pg-item.pg-active > a:hover { color: #fff; border-color: #0077db; background-color: #0077db; } .pg-pager .pg-item:first-child a { border-radius: 3px 0 0 3px; } .pg-pager .pg-item:last-child a { border-radius: 0 3px 3px 0; } .pg-pager .pg-item.pg-ellipsis > span { cursor: not-allowed; } .pg-pager .pg-item.pg-ellipsis > span:hover { color: inherit; border-color: #ccc; background-color: transparent; } .pg-pager .pg-item.pg-disabled { cursor: not-allowed; } .pg-pager .pg-item.pg-disabled a { opacity: 0.6; pointer-events: none; } .pg-pager .pg-item.pg-disabled a:hover { color: inherit; border-color: #ccc; background-color: transparent; } .btn { border-radius: 3px; font-size: 14px; font-family: "Roboto"; font-weight: 500; } .btn.btn-primary { border-color: #0077db; background-color: #0077db; } .btn.btn-primary:hover { background-color: #007fea; } .btn.btn-danger { border-color: #fa424a; background-color: #fa424a; } .btn.btn-danger:hover { background-color: #fa5158; } .pagination { margin: 0; font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; }
4. Finally, add the following JavaScript function to activate the dynamic pagination.
(function(root) { "use strict"; var win = window, doc = document, body = doc.body; /** * Default configuration * @typ {Object} */ var defaultConfig = { limit: 0, offset: 2, startPage: 1, hideDisabled: true, prevNext: true, prevText: "‹", nextText: "›", firstLast: false, firstText: "«", lastText: "»", ellipsisText: "…", hashString: "#", classes: { pager: "pg-pager", item: "pg-item", link: "pg-link", prev: "pg-prev", next: "pg-next", first: "pg-first", last: "pg-last", active: "pg-active", disabled: "pg-disabled", ellipsis: "pg-ellipsis", } }; /** * Check is item is object * @return {Boolean} */ var isObject = function(val) { return Object.prototype.toString.call(val) === "[object Object]"; }; /** * Check is item is array * @return {Boolean} */ var isArray = function(val) { return Array.isArray(val); }; var closest = function(el, fn) { return el && el !== body && (fn(el) ? el : closest(el.parentNode, fn)); }; /** * Merge objects (reccursive) * @param {Object} r * @param {Object} t * @return {Object} */ var extend = function(src, props) { for (var prop in props) { if (props.hasOwnProperty(prop)) { var val = props[prop]; if (val && isObject(val)) { src[prop] = src[prop] || {}; extend(src[prop], val); } else { src[prop] = val; } } } return src; }; /** * Iterator helper * @param {(Array|Object)} arr Any object, array or array-like collection. * @param {Function} fn Callback * @param {Object} scope Change the value of this * @return {Void} */ var each = function(arr, fn, scope) { var n; if ( Number.isInteger(arr) ) { for (n = 0; n < arr; n++) { fn.call(scope, n + 1, n); } } else { if (isObject(arr)) { for (n in arr) { if (Object.prototype.hasOwnProperty.call(arr, n)) { fn.call(scope, arr[n], n); } } } else { for (n = 0; n < arr.length; n++) { fn.call(scope, arr[n], n); } } } }; /** * Add event listener to target * @param {Object} el * @param {String} e * @param {Function} fn */ var on = function(el, e, fn) { el.addEventListener(e, fn, false); }; /** * Create DOM element node * @param {String} a nodeName * @param {Object} b properties and attributes * @return {Object} */ var createNode = function(a, b) { var d = doc.createElement(a); if (b && "object" == typeof b) { var e; for (e in b) { if ("html" === e) { d.innerHTML = b[e]; } else { d.setAttribute(e, b[e]); } } } return d; }; var getPage = function(e) { return parseInt(e.getAttribute("data-page"), 10); }; var Pager = function(config) { this.config = extend(defaultConfig, config); this.container = this.config.container; if (typeof this.container === "string") { this.container = document.querySelector(this.container); } if ( this.config.pages ) { this.totalPages = this.config.pages; } this.limit = this.config.limit; this.offset = this.config.offset; this.hideDisabled = this.config.hideDisabled; this.bindEvents(); if ( this.config.startPage ) { this.goTo(this.config.startPage); } var that = this; setTimeout(function() { that.emit("init", that.currentPage); }, 10); }; Pager.prototype.bindEvents = function() { this.events = { click: this.click.bind(this) }; on(this.container, "click", this.events.click); }; Pager.prototype.click = function(e) { var that = this, target = e.target, o = that.config; var item = closest(target, function(node) { return node.item; }); if ( item ) { e.preventDefault(); if (item.ellipsis) { return; } that.goTo(parseInt(item.dataset.page, 10)) } }; Pager.prototype.render = function(pages) { var that = this, o = that.config, node = document.createDocumentFragment(); if ( pages ) { that.items = []; that.totalPages = pages; if ( that.currentPage > that.totalPages ) { that.currentPage = that.totalPages; } } if ( that.pager ) { that.pager.className = o.classes.pager; } else { that.pager = createNode("ul", { class: o.classes.pager }); } var items = that.truncate(); if ( that.hideDisabled && that.currentPage === 1 ) { } else { if ( o.firstLast ) { that.first = that.renderButton({ class: o.classes.first, content: o.firstText, page: 1, nav: true, first: true }); node.appendChild(that.first); } if ( o.prevNext ) { that.prev = that.renderButton({ class: o.classes.prev, content: o.prevText, page: that.currentPage > 1 ? that.currentPage - 1 : 1, nav: true, prev: true }); node.appendChild(that.prev); } } each(items, function(item, i) { node.appendChild(item); }); if ( that.hideDisabled && that.currentPage === that.totalPages ) { } else { if ( o.prevNext ) { that.next = that.renderButton({ class: o.classes.next, content: o.nextText, page: that.currentPage < that.totalPages ? that.currentPage + 1 : that.totalPages, nav: true, next: true }); node.appendChild(that.next); } if ( o.firstLast ) { that.last = that.renderButton({ class: o.classes.last, content: o.lastText, page: that.totalPages, nav: true, last: true }); node.appendChild(that.last); } } that.pager.innerHTML = ""; that.pager.appendChild(node); that.container.appendChild(that.pager); that.emit("render"); }; Pager.prototype.renderButton = function(obj) { var that = this, o = that.config; var item = createNode("li", { class: o.classes.item }); item.dataset.page = obj.page; if ( obj.page === that.currentPage && !obj.ellipsis && !obj.nav) { item.classList.add(o.classes.active); } var link = createNode(obj.ellipsis ? "span" : "a", { class: !obj.ellipsis ? o.classes.link : "", html: obj.content }); if ( obj.class ) { item.classList.add(obj.class); } if ( obj.nav ) { item.nav = true; } if ( obj.ellipsis ) { item.ellipsis = true; } else { item.item = true; link.href = o.hashString.replace("{page}", obj.page).replace("{pages}", that.totalPages); } if ( (obj.prev || obj.first) && that.currentPage === 1 || (obj.next || obj.last) && that.currentPage === that.totalPages ) { item.disabled = true; item.classList.add(o.classes.disabled); link.tabIndex = -1; } else { item.disabled = false; } item.appendChild(link); return item; }; Pager.prototype.goTo = function(page) { var that = this, o = that.config; if ( o.ajax ) { o.ajax.data = o.ajax.data || {} o.ajax.data[o.ajax.param || "page"] = page; // https://stackoverflow.com/questions/316781/how-to-build-query-string-with-javascript/34209399#34209399 var esc = encodeURIComponent; var query = Object.keys(o.ajax.data) .map(k => esc(k) + '=' + esc(o.ajax.data[k])) .join('&'); var request = new Request(o.ajax.url + "?" + query, { method: "GET", headers: new Headers() }); if ( typeof o.ajax.before === "function" ) { o.ajax.before.call(that, data); } fetch(request).then(function (response) { return response.json(); }) .then(function (data) { that.currentPage = page; if ( typeof o.ajax.success === "function" ) { o.ajax.success.call(that, data); } that.render(); that.emit("change", page); }); } else { that.currentPage = page; that.render(); that.emit("change", page); } }; Pager.prototype.truncate = function() { var that = this; var page = that.currentPage; var pages = that.totalPages; var delta = that.offset; var offset = delta * 2; var left = page - delta; var right = page + delta; var range = []; var pager = []; var k; // No need to truncate if the number of pages is low if (!this.limit || this.totalPages <= this.limit) { each(pages, function(index) { pager.push(that.renderButton({ page: index, content: index })); }); } else { if ( page < (4 - delta) + offset ) { right = 3 + offset; } else if ( page > pages - ((3 - delta) + offset) ) { left = pages - (2 + offset); } for (let i = 1; i <= pages; i++) { if (i == 1 || i == pages || i >= left && i <= right) { range.push(that.renderButton({ page: i, content: i })); } } each(range, (link) => { var page = getPage(link); if (k) { var p = getPage(k); if (page - p == 2) { pager.push(that.renderButton({ page: p + 1, content: p + 1 })); } else if (page - p != 1) { pager.push(that.renderButton({ class: that.config.classes.ellipsis, content: that.config.ellipsisText, ellipsis: true })); } } pager.push(link); k = link; }); } return pager; }; Pager.prototype.add = function() { this.render(this.totalPages + 1); this.emit("add"); }; Pager.prototype.remove = function(num) { if (this.totalPages > 1) { this.render(this.totalPages - 1); this.emit("remove"); } }; Pager.prototype.on = function(event, fct) { this.events[event] = this.events[event] || []; this.events[event].push(fct); }; Pager.prototype.off = function(event, fct) { if (event in this.events === false) return; this.events[event].splice(this.events[event].indexOf(fct), 1); }; Pager.prototype.emit = function(event /* , args... */) { if (event in this.events === false) return; for (var i = 0; i < this.events[event].length; i++) { this.events[event][i].apply( this, Array.prototype.slice.call(arguments, 1) ); } }; Pager.prototype.set = function(prop, value) { this[prop] = value; }; Pager.prototype.setLimit = function(limit) { this.limit = parseInt(limit, 10); }; Pager.prototype.setOffset = function(offset) { this.offset = parseInt(offset, 10); }; Pager.prototype.getLimit = function() { return this.limit; }; Pager.prototype.getOffset = function() { return this.offset; }; root.Pager = Pager; })(this); const config = { container: "#pager", limit: 10, // startPage: 10, firstLast: true, hideDisabled: false, hashString: "?page={page}", prevText: '<span class="mdi mdi-chevron-left"></span>', nextText: '<span class="mdi mdi-chevron-right"></span>', firstText: '<span class="mdi mdi-chevron-double-left"></span>', lastText: '<span class="mdi mdi-chevron-double-right"></span>', ellipsisText: '<span class="mdi mdi-dots-horizontal"></span>', }; const pager = new Pager(config) pager.render(20); /* DEMO STUFF */ const $ = el => document.getElementById(el); const $$ = el => document.querySelectorAll(el); const classes = pager.config.classes; const limit = $("limit"); const offset = $("offset"); const pages = $("pages"); const page = $("page"); const info = $("info"); const trunc = $("truncation"); const truncs = $$(".truncation"); const hide = $("hideDisabled"); const hides = $$(".hide-disabled"); const skin = $("skin"); const skins = $$(".skin"); pager.on("init", init); pager.on("render", update) pager.on("change", update); pager.on("add", update); pager.on("remove", update); skin.addEventListener("change", changeSkin, false); hide.addEventListener("change", e => { var input = e.target; var val = parseInt(input.value, 10); pager.set("hideDisabled", val ? true : false); pager.render(); }, false); trunc.addEventListener("change", e => { var input = e.target; var val = parseInt(input.value, 10); var shitTonsOfLinks = false; if ( !val && parseInt(pages.value, 10) >= 1000 ) { shitTonsOfLinks = !confirm("You have a shit-ton of pages!! Are you sure you want to disable truncation and render all the links?"); } if ( !shitTonsOfLinks ) { pager.setLimit(val ? limit.value : val); pager.render(); limit.disabled = !val; offset.disabled = !val; } else { truncs[0].checked = true; } }, false); pages.addEventListener("change", e => { var max = parseInt(pages.value, 10); var val = parseInt(page.value, 10); pager.render(max); page.max = max; if ( val > max ) { page.value = max } }, false); page.addEventListener("change", e => { pager.goTo(parseInt(page.value, 10)); }, false); limit.addEventListener("change", e => { pager.setLimit(limit.value); pager.render(); }, false); offset.addEventListener("change", e => { pager.setOffset(offset.value); pager.render(); }, false); function init() { limit.disabled = !truncs[0].checked; offset.disabled = !truncs[0].checked; skins[0].checked = true; hides[0].checked = true; truncs[0].checked = true; pages.value = 20; page.value = 1; page.max = 20; limit.value = 10; offset.value = 2; update(); } function update() { page.value = pager.currentPage; info.textContent = `Page ${pager.currentPage} of ${pager.totalPages}`; } function changeSkin(e) { var val = e.target.value; if ( val === "bootstrap" ) { pager.config.prevText = "‹"; pager.config.nextText = "›"; pager.config.firstText = "«"; pager.config.lastText = "»"; pager.config.ellipsisText = "…"; pager.config.classes = { pager: "pagination", item: "page-item", link: "page-link", prev: "page-item", next: "page-item", first: "page-item", last: "page-item", active: "active", disabled: "disabled", ellipsis: "page-link", }; } else { pager.config.classes = classes; pager.config.prevText = '<span class="mdi mdi-chevron-left"></span>'; pager.config.nextText = '<span class="mdi mdi-chevron-right"></span>'; pager.config.firstText = '<span class="mdi mdi-chevron-double-left"></span>'; pager.config.lastText = '<span class="mdi mdi-chevron-double-right"></span>'; pager.config.ellipsisText = '<span class="mdi mdi-dots-horizontal"></span>'; } pager.render(); }
That’s all! hopefully, you have successfully created Dynamic Pagination in JavaScript. If you have any questions or suggestions, feel free to comment below.
Similar Code Snippets:
I code and create web elements for amazing people around the world. I like work with new people. New people new Experiences.
I truly enjoy what I’m doing, which makes me more passionate about web development and coding. I am always ready to do challenging tasks whether it is about creating a custom CMS from scratch or customizing an existing system.