Skip to content

Instantly share code, notes, and snippets.

@kuroneko46 kuroneko46/pagination.js
Last active Jun 24, 2019

Embed
What would you like to do?
Javascript Create Pagination HTML sample. (fixed page length.)
function pagination(opt) {
const def = {
link: '/',
current: 1,
perPage: 5,
total: 1,
viewPageNum: 9,
query: {},
}
const options = Object.assign(def, opt);
const lastPage = Math.ceil(options.total / options.perPage);
const offsetLeft = Math.floor((options.viewPageNum - 1) / 2);
const offsetRight = options.viewPageNum - offsetLeft - 1;
let start = options.current - offsetLeft;
let end = options.current + offsetRight;
if (options.current - offsetLeft < 1) {
start = 1;
end = start + (options.viewPageNum < lastPage ? options.viewPageNum : lastPage) - 1;
} else if (options.current + offsetRight > lastPage) {
start = lastPage - (options.viewPageNum < lastPage ? options.viewPageNum : lastPage) + 1;
end = lastPage;
}
const params = []
if (options.query) {
for (const key in options.query) {
params.push(`${key}=${encodeURI(options.query[key])}`);
}
}
let output = '<div class="paginator">';
const firstURL = options.link + '?' + params.concat([`page=1`]).join('&');
const lastURL = options.link + '?' + params.concat([`page=${lastPage}`]).join('&');
if (options.current > 1) {
output += `<a href="${firstURL}">≪</a>`;
}
for (let i = start; i <= end; i++) {
const paramsWithPage = params.concat([`page=${i}`]);
const url = options.link + '?' + paramsWithPage.join('&');
if (i == options.current) {
output += `<a href="${url}" class="paginator-current">${i}</a>`;
} else {
output += `<a href="${url}">${i}</a>`;
}
}
if (options.current < lastPage) {
output += `<a href="${lastURL}">≫</a>`;
}
output += '</div>';
return output;
}
module.exports = pagination;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.