Skip to content

Instantly share code, notes, and snippets.

@daler445
Last active September 19, 2019 11:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daler445/3167cafc80e85d8e642d01c499c98d62 to your computer and use it in GitHub Desktop.
Save daler445/3167cafc80e85d8e642d01c499c98d62 to your computer and use it in GitHub Desktop.
Smart pagination
//Output with default params: 1 14 15 [16] 17 18 25
function generatePagination(url = "#", totalPages = 25, limitPerSide = 2, current = 16, showFirst = true, showLast = true) {
var output = "";
var hasFirst = false;
var hasLast = false;
if ( current === 1 ) {
hasFirst = true;
}
if ( current === totalPages ) {
hasLast = true;
}
for (var page = (current - limitPerSide); page < current; page++) {
if ( page <= 0 ) {
continue;
}
if ( hasFirst === false && page === 1 ) {
hasFirst = true;
}
output += wrapPaginationLink(url, page, false);
}
output += wrapPaginationLink(url, current, true);
for (var page = current + 1; page <= (current + limitPerSide); page++ ) {
if ( page >= totalPages ) {
continue;
}
if ( hasLast === false && page === totalPages ) {
hasLast = true;
}
output += wrapPaginationLink(url, page, false);
}
if (showFirst === true) {
if (hasFirst === false) {
output = wrapPaginationLink(url, 1, false) + output;
}
}
if (showLast === true) {
if (hasLast === false) {
output += wrapPaginationLink(url, totalPages, false);
}
}
console.log(output);
}
function wrapPaginationLink(url, page, active = false) {
var activeClass = "";
if (active === true) {
activeClass = "active";
}
return "<li class='"+activeClass+"' onclick='changePage(\""+url+"\", "+page+")'>"+page+"</li>";
}
function generatePagination(data = 1, total = 10, limitPerSide = 2, current = 5) {
for ( var page = 1; page < total; page++ ) {
if ( page < current ) {
if ( (page + limitPerSide) < current ) {
console.log('hide ' + page);
} else {
console.log('show ' + page);
}
}
if (page === current) {
console.log('current ' + page);
}
if ( page > current ) {
if ( (current + limitPerSide) >= page ) {
console.log('show ' + page);
} else {
console.log('hide ' + page);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment