Skip to content

Instantly share code, notes, and snippets.

@kenny-lee-1992
Created January 25, 2019 02:17
Show Gist options
  • Save kenny-lee-1992/9b72e8864478fe39e1b14b39299175d1 to your computer and use it in GitHub Desktop.
Save kenny-lee-1992/9b72e8864478fe39e1b14b39299175d1 to your computer and use it in GitHub Desktop.
Generate paging with js
public paging(current, pagesize, total) {
const totalpages = Math.ceil(total / pagesize);
const pageInfo = {
// Assign to the scope in paging
totalpages: totalpages,
// clear array before pushing new items
pageArr: [],
};
// if page is 1 or 0 return, no need of paging
if (totalpages <= 1) {
return pageInfo;
}
if (totalpages <= 5) {
for (let i = 1; i <= totalpages; i++) {
pageInfo.pageArr.push(i);
}
}
if (totalpages > 5) {
if (current <= 3) {
for (let i = 1; i <= 5; i++) {
pageInfo.pageArr.push(i);
}
pageInfo.pageArr.push('...');
pageInfo.pageArr.push(totalpages);
pageInfo.pageArr.push('Next');
} else if (totalpages - current <= 3) {
pageInfo.pageArr.push('Prev');
pageInfo.pageArr.push(1);
pageInfo.pageArr.push('..');
for (let i = totalpages - 4; i <= totalpages; i++) {
pageInfo.pageArr.push(i);
}
} else {
pageInfo.pageArr.push('Prev');
pageInfo.pageArr.push(1);
pageInfo.pageArr.push('..');
for (let i = current - 2; i <= current + 2; i++) {
pageInfo.pageArr.push(i);
}
pageInfo.pageArr.push('...');
pageInfo.pageArr.push(totalpages);
pageInfo.pageArr.push('Next');
}
}
return pageInfo;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment