Reputation: 3080
I'm trying to generate pagination buttons.
I want the buttons to look like this:
The bold number is the selected page, 7 is the highest page.
My current function generates this up until the point where you're on the last 3 pages.
[1, 2, 3, "...", 7]
[2, 3, 4, "...", 7]
[3, 4, 5, "...", 7]
[4, 5, 6, "...", 7]
[5, 6, 7]
[6, 7]
[7]
What I want it to look like:
[1, 2, 3, "...", 7]
[2, 3, 4, "...", 7]
[3, 4, 5, "...", 7]
[4, 5, 6, "...", 7]
[5, 6, 7]
[5, 6, 7]
[5, 6, 7]
Javascript:
var test = function (count, current) {
this.pageCountArray = [];
var shownPageNumbers = 3;
for (var i = current; i <= count; i++) {
if (this.pageCountArray.length < shownPageNumbers) {
this.pageCountArray.push(i);
}
else {
this.pageCountArray.push('...');
this.pageCountArray.push(count);
break;
}
}
console.log(this.pageCountArray);
}
Usage:
test(7, 1);
test(7, 2);
test(7, 3);
test(7, 4);
test(7, 5);
test(7, 6);
test(7, 7);
console.clear();
var test = function (count, current) {
this.pageCountArray = [];
var shownPageNumbers = 3;
for (var i = current; i <= count; i++) {
if (this.pageCountArray.length < shownPageNumbers) {
this.pageCountArray.push(i);
}
else {
this.pageCountArray.push('...');
this.pageCountArray.push(count);
break;
}
}
console.log(this.pageCountArray);
document.write(JSON.stringify(this.pageCountArray))
}
test(7, 1);
test(7, 2);
test(7, 3);
test(7, 4);
test(7, 5);
test(7, 6);
test(7, 7);
Upvotes: 2
Views: 7057
Reputation: 96
Your issue is that you are populating your array only from current
to count
. So, when you get to values for current
that are above count - (shownPageNumbers - 1)
, you need to have the for loop start from count - (shownPageNumbers - 1)
instead of just current
, in order to show the correct amount of page numbers.
You could add an if statement before the for loops checking if (current > (count - (shownPageNumbers - 1)) and update current to that, or in your for loop set i = min(current, (count - (shownPageNumbers - 1))
Upvotes: 2
Reputation: 2244
Here is how I would implement it:
function pageNumbers(count, current) {
var shownPages = 3;
var result = [];
if (current > count - shownPages) {
result.push(count - 2, count - 1, count);
} else {
result.push(current, current + 1, current + 2, '...', count);
}
return result;
}
Example: http://jsfiddle.net/howderek/x474jtsd/
Upvotes: 9