Skip to content

Instantly share code, notes, and snippets.

@ammmze
Created March 22, 2013 19:15
Show Gist options
  • Save ammmze/5223929 to your computer and use it in GitHub Desktop.
Save ammmze/5223929 to your computer and use it in GitHub Desktop.
Gets the nearest x pages. Useful for pagination where there may be many results, but you only want to display a max of X pages. It will always put the current page in the middle, except if num_to_show is odd, if its even, it will be in the middle, with the one extra on left.
/**
* Gets the nearest x pages.
*
* Useful for pagination where there may be many results, but you only want to display a max of X pages.
* It will always put the current page in the middle, except if num_to_show is odd, if its even, it will be in the
* middle, with the one extra on left.
*/
function getNearestPages(current_page, total_pages, num_to_show) {
var near_pages = [];
var num_to_show = 3;
var mid = Math.round(num_to_show / 2);
var start = (current_page + mid - num_to_show);
if (start < 1) {
start = 1;
}
if (start+num_to_show > total_pages) {
start = total_pages - num_to_show + 1;
}
for (var i = start; i < start+num_to_show; i++) {
if (i >= 1 && i <= total_pages) {
near_pages.push({
number : i,
current : (i == current_page)
});
}
}
return near_pages;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment