JavaScript Pagination Only show 5 buttons - javascript

I have created a pagination system using JavaScript. I have used this code to create the pagination system:
function setUpPagination(items, wrapper, rows_per_page) {
wrapper.innerHTML = "";
let page_count = Math.ceil(items.length / rows_per_page);
for (let i = 1; i < page_count + 1; i++) {
let btn = paginationButton(i, items);
wrapper.appendChild(btn);
}
}
function paginationButton(page, items) {
let button = document.createElement('button');
button.innerText = page;
if (current_page == page) {
button.classList.add('active');
}
button.addEventListener('click', function() {
current_page = page;
displayList(items, list_element, rows, current_page);
let current_btn = document.querySelector('.pagination button.active');
current_btn.classList.remove('active');
button.classList.add('active');
})
return button;
}
However, this code shows all of the pagination buttons. If I have 100 pages, all 100 pagination buttons will be shown.
I only want to show 5 buttons at a time. These buttons should be: the page the user is currently on, the 2 pages before the page the user is currently on, the 2 pages after the page the user is currently on.
If the user is on page 1, pages 1 - 5 should be shown.
If the user is on the last page, the last page button and the 4 page buttons before that should be shown.
I have added this code to stop the user from selecting a page which is too high:
if (i >= page_count) {
i = page_count;
}
However this means the user cannot select the last two pages.
I want to give the user the ability to select the last two pages. However, no extra pages should be shown.

With the way you have set up your for-loop bounds in your setUpPagination function, you are iterating over every single page and making a button for each one. I recommend you update the loop bounds to only cover the range of pages you want buttons for.
I envision an update that looks something like this:
for (let i = current_page - 2; i <= current_page + 2; i++) { // <-- HERE!
let btn = paginationButton(i, items);
wrapper.appendChild(btn);
}
}
Of note, this won't properly account for when you are looking at the first few or last few pages, so you will want to update this slightly to account for these edge cases (for example, if you are viewing page 1 currently this would attempt to make buttons for pages -1, 0, 1, 2, & 3). I think this should give you a good push in the right direction though!

This function will return five pages, current in the middle and first/last five if necessary:
const result = getPages(3, 19);
console.log(result);
function getPages(totalPages, currentPage) {
if (totalPages <= 5) return Array.from(Array(totalPages).keys()).map( r => { return r + 1 });
let diff = 0;
const result = [currentPage - 2, currentPage - 1, currentPage, currentPage + 1, currentPage + 2];
if (result[0] < 3 ) {
diff = 1 - result[0];
}
if (result.slice(-1) > totalPages - 2 ) {
diff = totalPages - result.slice(-1);
}
return result.map( r => { return r + diff });
}
Case total 5, current from 1 to 5 returns [1,2,3,4,5].
Case total less than 5, returns an array of number of total length.
Case total 15, current 13, 14 or 15 returns [11,12,13,14,15].

Related

Bird Watcher Exercism Javascript Solution - counter not counting

I'm trying to figure out an exercise from Exercism's Javascript track. It is an exercise using for loops called Bird Watcher.
The instructions say to initialize a function called birdsInWeek that takes two arguments. First is an array 'birdsPerDay', and the second is 'week'. Given the birdsPerDay array, the function is supposed to count the total number of birds seen in the specified week. So, if 'week' = 1, for example, the corresponding indexes of 'birdsPerDay' to add together would be 0 - 6, and so on and so forth.
I have tested my code using the provided test cases and in the Chrome console. I tried logging some values to understand where the bug is, but I can't figure out why my counter (named 'totalBirdsInSpecifiedWeek'), which is initialized to '0' is staying at '0' instead of adding the corresponding indexes of 'week' together and return the correct 'totalBirdsInSpecifiedWeek'. I have tried changing the placement of the return statement as well, but that didn't result in any change.
Below is the code I have written:
export function birdsInWeek(birdsPerDay, week) {
let totalBirdsInSpecifiedWeek = 0
if (week === 1) {
for (let i = 0; i < birdsPerDay[7]; i++) {
totalBirdsInSpecifiedWeek += birdsPerDay[i];
}
return totalBirdsInSpecifiedWeek;
} else {
for (let i = week * 7 - 7; i < birdsPerDay[week * 7]; i++) {
totalBirdsInSpecifiedWeek += birdsPerDay[i];
}
return totalBirdsInSpecifiedWeek;
};
}
Where did I go wrong?
birdsPerDay[7] this means values of birdsPerDay array at index 7 of the array
so the condition would loop checking if i is lesser than that value sometimes it would even hit the NaN so the idea is to just check on either length or index of the array to get an accurate response ..
Per the commenter #gog, I changed the 4th and 9th lines of code to correct the stopping condition in each of the for loops so they are written as indexes of the 'birdsPerDay' array and instead just numerical values.
export function birdsInWeek(birdsPerDay, week) {
let totalBirdsInSpecifiedWeek = 0
if (week === 1) {
for (let i = 0; i < 7; i++) {
totalBirdsInSpecifiedWeek += birdsPerDay[i];
}
return totalBirdsInSpecifiedWeek;
} else {
for (let i = week * 7 - 7; i < week * 7; i++) {
totalBirdsInSpecifiedWeek += birdsPerDay[i];
}
return totalBirdsInSpecifiedWeek;
}; return totalBirdsInSpecifiedWeek;
}
I found the exercise, according to the problem posed, I think this is the solution.
bird-watcher - exercism
Explanation, the array is divided by the days of the week, then the array is divided by that amount from 0 to 6 (Monday to Sunday), then I used a nested "for" to iterate over the corresponding week, I used another "for" to do the addition, return the value from the function and return the result.
let countsbirdsPerDay = [2, 5, 0, 7, 4, 1, 3, 0, 2, 5, 0, 1, 3, 1];
let userWeek = 2;
const birdsInWeek = (birdsPerDay, week) => {
let segmentWeek = Math.round(birdsPerDay.length / week);
let total = 0;
for (let i = 0; i < week; i++) {
views = birdsPerDay.slice(i * segmentWeek, segmentWeek * (i + 1));
if ((i + 1) == week) {
for (let x = 0; x < views.length; x++) {
total = total + views[x];
}
}
}
return total;
}
console.log(birdsInWeek(countsbirdsPerDay, userWeek));

How to make an algorithm for complex pagination in JS?

I'm trying to make pagination work but it's a bit complex for me so I need help. If someone has an idea how to make it, I would be thankful.
I need to show items that the user owns. One page can have maximum of 12 items displayed.
I have a pageData array, that returns the number of items for a category. Category "shirts" has 2 items.
pageData = [ {id:'pants',totalItems: 15},
{id:'shirts',totalItems: 2}, {id:'dresses',totalItems: 13}]
On first load I need to show 12 items (lets say 12 pants), on second load (click on load more button) I need to show 3 more pants, 2 shirts and 7 dresses.
Metadata for an item has to be fetched via api (this is just an example how to get id of specific item, I'm trying to put it somehow into code but don't have clear idea how):
for (let i = 0; i < pageData['pants'].totalItems; i++) {
const metadata = await api.getMetadata({
userId: 'userId',
id: i,
});
}
This is some code that I have but like I said, I don't really have an idea how to make it:
const getItems = async (pageData, currentPage) => {
const itemsPerPage = 12;
let fetchedData = [];
let total = 0;
let start = currentPage * itemsPerPage;
for (let i = 0; i < pageData.length; i++) {
const minRange = total;
const maxRange = minRange + itemsPerPage;
if (start >= minRange && start <= maxRange) {
const minId = minRange - total;
const maxId = maxRange - total;
for (let j = minId; j < maxId; j++) {
const metadata = await api.getMetadata({
userId: 'userId',
id: j,
});
fetchedData.push(metadata);
}
}
total += itemsPerPage;
}
};

Javascript Iteration to display custom list with pause/stop jquery fadeIn and fadeOut

I have an array that is constantly being updated, and needs to display the items in the array 5 at a time. Sometimes there are more than 5 elements in the array, sometimes there are less. If there are more than 5 elements in the array, then I need to cycle them 5 at a time. For example, if there are 10 elements, I want to fade in 1-5, then fade out 1-5, then fade in 5-10. I have this working, and updating, however, if there are only 4 news articles available after the data update, it still fades in and out 1-4, over and over. I need to always fade in the first articles, and if there are less than the numberToShow, don't fade out, just update.
I have tried clearInterval, but that stops updating. I tried .stop().fadeOut(); but then the fade in keeps occurring. I tried .stop().fadeOut(); with .stop().fadeIn(); but the data never fades in. Should I pass the array in to display it, and cycle in there?
For testing, this is simulated with using the date. Every 8 seconds it should update the the data with an updated number. If there are 4 articles, fade in, and update the Date.now() number, but never fade out. If there are 10 articles, fade in and update each cycle.
var numberToShow = 5;
var newsArray = [];
var startRow = 0;
var endRow = 0;
function getData() {
// Simulate the data changing using date.
newsArray = [Date.now(), "News article 1", "News article 2", "News article 3", "News article 4",
"News article 5", "News article 6", "News article 7", "News article 8", "News article 9"];
showNews(numberToShow);
}
// Fade out the results for the next cycle
setInterval(function() {
$("span.text").fadeOut({
duration: 800
});
setTimeout(
function() {
getData();
},
(800)
);
}, 8000);
// Update the data
function updateData() {
getData();
setTimeout(updateData, 6000);
}
// Display the results
function showNews() {
if (endRow >= newsArray.length) {
startRow = 0;
}
endRow = startRow + numberToShow;
if (endRow >= newsArray.length) {
endRow = newsArray.length;
}
var results = "";
for (var k = startRow; k < endRow; k++) {
results += "<span class='text' style='display:none;'>" + newsArray[k] + "</span><br>";
}
startRow = startRow + numberToShow;
document.getElementById('showResults').innerHTML = results;
$("span.text").fadeIn({
duration: 800
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="showResults"></div>
While previous answer works fine - this one could be more like the case in your description...
Short description of the idea:
show list or the part of it.
if list is longer - repeat (go to step 1 in a couple of secs to show another part of the list)
when update comes - anytime - start again with new array
And working example (removed unneeded code and added button to help with tests):
var
numberToShow = 5,
newsArray = [],
startRow = 0,
endRow = 0,
$results = $("#showResults"),
timer;
function getData() {
// Simulate the data changing
newsArray = [Date.now()];
// add random number of items
var j = Math.floor(Math.random()*7)+1;
for(var i=0; i<j; i++){
newsArray.push('News article '+i);
}
// add one more item named "last"
newsArray.push('Last News article');
startCycle();
}
function startCycle() {
startRow = 0;
endRow = 0;
$results.fadeOut(800, function(){
renderList();
});
}
function renderList() {
if (endRow >= newsArray.length) {
startRow = 0;
}
endRow = startRow + numberToShow;
if (endRow > newsArray.length) {
endRow = newsArray.length;
}
var results = "";
for (var k = startRow; k < endRow; k++) {
results += "<span class='text'>" + newsArray[k] + "</span><br>";
}
startRow = startRow + numberToShow;
$results.html(results);
$results.fadeIn(800, function(){
nextCycle();
});
}
function nextCycle() {
// start cycling only if there is more results to be shown
if(newsArray.length > numberToShow){
timer = setTimeout(function(){
$results.fadeOut(800, function(){
renderList();
});
}, 4000);
}
}
// update on request
function updateData() {
clearTimeout(timer);
$results.stop();
getData();
}
// add button for tests
$results.before(
$('<button/>').text('Update now').click(function(){
updateData();
})
)
getData();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="showResults"></div>
Ok - not sure what exactly you tried to do - but you will easily change my code into anything you need
...lets start with clear algorithm:
getData
fade out if list is visible ...then continue to step 3.
render next portion of items from array
fade in if list is not visible ...then go to step 5.
wait a while...
check if all items has been shown (if not - show next portion with step 2, if so - update data with step 1)
hope the the code will give you a chance to adopt it to your needs:
var
numberToShow = 5,
newsArray = [],
startRow = 0,
endRow = 0,
$results = $("#showResults"),
visible = false,
timer;
function fadeInIfNeeded(callback) {
var is_visible = visible;
visible = true;
if(is_visible){
callback();
}else{
$results.fadeIn(800, callback);
}
}
function fadeOutIfNeeded(callback) {
var is_visible = visible;
visible = false;
if(is_visible){
$results.fadeOut(800, callback);
}else{
callback();
}
}
function getData() {
// Simulate the data changing
newsArray = [Date.now()];
// add random number of items
var j = Math.floor(Math.random()*6)+2;
for(var i=1; i<j; i++){
newsArray.push('News article '+i);
}
// add one more item named "last"
newsArray.push('Last News article');
startCycle();
}
function startCycle() {
startRow = 0;
endRow = 0;
fadeOutIfNeeded(function(){
renderList();
});
}
function renderList() {
if (endRow >= newsArray.length) {
startRow = 0;
}
endRow = startRow + numberToShow;
if (endRow > newsArray.length) {
endRow = newsArray.length;
}
var results = "";
for (var k = startRow; k < endRow; k++) {
results += "<span class='text'>" + newsArray[k] + "</span><br>";
}
startRow = startRow + numberToShow;
$results.html(results);
fadeInIfNeeded(function(){
nextCycle();
});
}
function nextCycle() {
// every portion of data will be seen for 6 + 0.8 + 0.8 = 7.6 sec
timer = setTimeout(function(){
if(startRow >= newsArray.length){
// if all items has been shown - get new data (update)
getData();
}else{
// if there is more to show - fade out and render
fadeOutIfNeeded(function(){
renderList();
});
}
}, 6000);
}
getData();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="showResults"></div>
Here is a modern view of how to implement your use case. Please note there
is not a single global variable and all DOM changes (side effects) occur in a single function.
You describe a constantly changing array. This code produces that array of integers
with one remarkable difference. After the data is set/retrieved, a Custom Event
is produced and fired. That event carries the changed/updated array.
function newData(data) { // Random size of array (between 1-15)
const previousLength = data.length;
// ~50% of the time the array grows, otherwise it shrinks
data.length = (Math.random() > .5)?
data.length + Math.ceil(Math.random() * (7 - 1) + 1) :
Math.ceil(Math.random() * (4 - 1) + 1);
for (let i = previousLength; i < data.length; i++) {
data[i] = Math.ceil(Math.random() * (15 - 1) + 1);
}
let dataEvent = new CustomEvent('gotData', { detail: data});
document.getElementById('showResults').dispatchEvent(dataEvent);
}
Your question describes what is the need for a custom iterator that provides no more than 5
array elements for each iteration. The following code provides a Generator function that follows
JavaScript's iterator protocol by returning a result with a .value property
containing an array of no more than 5 elements and a .done property containing a Boolean indicating if there
is no futher data. The yield statement returns data or the return statement results in
.done being set to true to indicate there is no further data. (see the MDN articles for details)
function* nextSet(data = [], numberToShow = 5) {
let current = [];
let currentStart = 0;
while (true) {
[current] = [data.slice(currentStart, currentStart + numberToShow)];
if (currentStart < data.length) {
yield current;
} else {
return;
}
currentStart += numberToShow;
}
}
With the data and iterator in place this code starts off the procession. Set up
an event listener for the custom event, then get some mock data (starting with an
empty array):
document.getElementById('showResults').addEventListener('gotData', doDOM);
newData([]);
All the DOM work is done in the event callback function below (doDOM()).
First create an iterator from the Generator Function.
Then start the interval timer so that we can repeatedly call .next() on the iterator.
Please note how dead-simple the animation actually is with
a bit of rethinking the approach to the entire problem. If result is undefined
then cancel the interval timer, mock more data and repeat the process with the updated array.
function doDOM(event) {
const data = event.detail;
const iterator = nextSet(data); // create iterator from Generator
let text = '';
let page = 0;
let interval = setInterval(()=>{
page++;
let result = iterator.next().value;
if(result) {
text = `Array size: ${data.length} (Page ${page}) -- ${JSON.stringify(result)}`;
// Dead simple animations...
$(event.target).fadeOut(1000, () => {
event.target.innerText = text;
$(event.target).fadeIn(1000);
});
} else {
event.target.innerText += " ----> getting more data..."
// all done, so kill this one
clearInterval(interval);
// Mock new data arrival
newData(data);
return;
}
}, 5000);
}
I do realize this seems to be a mile off from your question. But this answer addresses the whole
puzzle rather than just one bit.
/**
* A Generator function to produce number of data elements
*/
function* nextSet(data = [], numberToShow = 5) {
let current = [];
let currentStart = 0;
while (true) {
[current] = [data.slice(currentStart, currentStart + numberToShow)];
if (currentStart < data.length) {
yield current;
} else {
return;
}
currentStart += numberToShow;
}
}
/**
* CustomEvent Handler - fired when new data is received
*
* DOM manipulations
* All side effects are contained within one function
* #parm Event - contains detail with data
*/
function doDOM(event) {
const data = event.detail;
const iterator = nextSet(data); // create iterator from Generator
let text = '';
let page = 0;
let interval = setInterval(() => {
page++;
let result = iterator.next().value;
if (result) {
text = `Array size: ${data.length} (Page ${page}) -- ${JSON.stringify(result)}`;
// Dead simple animations...
$(event.target).fadeOut(1000, () => {
event.target.innerText = text;
$(event.target).fadeIn(1000);
});
} else {
event.target.innerText += " ----> That's it! Getting more data..."
// all done, so kill this one
clearInterval(interval);
// Mock new data arrival
newData(data);
return;
}
}, 5000);
}
// Array that is either growing or changing on each call
function newData(data) { // Random size of array (between 1-15)
const previousLength = data.length;
// ~50% of the time the array grows, otherwise it shrinks
data.length = (Math.random() > .5) ?
data.length + Math.ceil(Math.random() * (7 - 1) + 1) :
Math.ceil(Math.random() * (4 - 1) + 1);
for (let i = previousLength; i < data.length; i++) {
data[i] = Math.ceil(Math.random() * (15 - 1) + 1);
}
let dataEvent = new CustomEvent('gotData', {
detail: data
});
document.getElementById('showResults').dispatchEvent(dataEvent);
}
document.getElementById('showResults').addEventListener('gotData', doDOM);
newData([]);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script defer src="index.js"></script>
</head>
<body>
<main id="showResults">Welcome! ----> waiting for data...</main>
</body>
</html>
Expand the code snippet to see this work.

Jquery click event causing loop to execute only one time

I want to show next five divs each time when i click show more button, 5 divs will be shown default when load, here is my code,
var counterBox = 5;
$("#show_more_location").click(function() {
$(".loading-container").show();
for (var inc = 5; inc <= 5; inc++) {
if(counterBox<50){
counterBox = counterBox + 1;
$(".location-box:nth-child("+counterBox+")").slideDown().addClass("show_box").delay(100);
}
}
$(".loading-container").delay(5000).hide();
});
Problem is that when I click show more button, it loops only once, and stops. Only one div is showing ,I want to show 5 divs on show buttonclick.
Can anyonehelp?
It seems you init your inc iterator with 5, and get out of the loop when it's higher than 5:
for (var inc = 5; inc <= 5; inc++) {
...
}
Try initializing it with 1:
for (var inc = 1; inc <= 5; inc++) {
...
}
You're setting inc in the for loop to 5, then checking if it is lower than or is 5. So it runs once. Make inc 0 to run it 6 times.

Javascript Google Style Pagination Menu

The math to correctly display a pagination menu via Javascript is driving me insane. Hopefully someone who understands this a little better than me can help me out.
All I need is to understand how to properly display a pagination menu on the client side with javascript.
Lets say I have 10 total items.
The max I want show at once is 1.
The menu should display 5 numbers and the last number should be the last page with a ... if we aren't on the last set of numbers.
So for instance < 1 2 3 4 ... 10 >
User clicks 2 - Start number should be 1, last 4 < 1 2 3 4 ... 10 >
User clicks 4 - start number should 2, last 5 < 2 3 4 5 ... 10 >
User clicks 5 - start should be 3, last 6 < 3 4 5 6 ... 10 >
User clicks 7 - we are on the last set so < 6 7 8 9 10 >
So far all I have is:
var pages = Math.ceil(count / amount);
var maxIterations = 5;
var iterations = Math.min(pages, maxIterations);
var offset = Math.max(0, page-Math.round(maxIterations/2));
for(var i=0; i<iterations; i++) {
var label = page + i;
if(i == maxIterations-1) label = pages; //Last page number
paginatorObjects.push({label: label}); //This create the menu button
}
Basically the point is that I need the numbers to iterate up and down as the user clicks through them (how google does it) without having to use the arrow buttons. I understand jQuery has a nice plugin for this sort of thing, but this has to be done in vanilla javascript.
This problem had me scratching my head for a while too, I recently had to implement it for an AngularJS application, but the pagination logic is pure javascript.
There's a working demo on CodePen at http://codepen.io/cornflourblue/pen/KVeaQL
I also wrote this blog post with further details
Here's the pagination logic
function GetPager(totalItems, currentPage, pageSize) {
// default to first page
currentPage = currentPage || 1;
// default page size is 10
pageSize = pageSize || 10;
// calculate total pages
var totalPages = Math.ceil(totalItems / pageSize);
var startPage, endPage;
if (totalPages <= 10) {
// less than 10 total pages so show all
startPage = 1;
endPage = totalPages;
} else {
// more than 10 total pages so calculate start and end pages
if (currentPage <= 6) {
startPage = 1;
endPage = 10;
} else if (currentPage + 4 >= totalPages) {
startPage = totalPages - 9;
endPage = totalPages;
} else {
startPage = currentPage - 5;
endPage = currentPage + 4;
}
}
// calculate start and end item indexes
var startIndex = (currentPage - 1) * pageSize;
var endIndex = startIndex + pageSize;
// create an array of pages to ng-repeat in the pager control
var pages = _.range(startPage, endPage + 1);
// return object with all pager properties required by the view
return {
totalItems: totalItems,
currentPage: currentPage,
pageSize: pageSize,
totalPages: totalPages,
startPage: startPage,
endPage: endPage,
startIndex: startIndex,
endIndex: endIndex,
pages: pages
};
}
What I ended up doing is this. This is directly from my source code, so there is some templating logic that doesn't make sense, but anyone who might be reading this in the future should be able to adjust according to their needs.
function paginate() {
var paginator = sb.find('#' + moduleName + 'Pagination')[0];
var container = paginator.getElementsByClass('container')[0];
sb.dom.clearAll(container);
if(count && count > 0) {
sb.dom.removeClass(paginator, 'hidden');
var pages = Math.ceil(count / amount);
var maxIterations = 5;
var iterations = Math.min(pages, maxIterations);
var paginatorObjects = [];
var center = Math.round(maxIterations/2);
var offset = page-center;
if(page < center) offset = 0; //Don't go lower than first page.
if(offset + iterations > pages) offset -= (offset + iterations) - pages; //Don't go higher than total pages.
for(var i=0; i<iterations; i++) {
var label = (i+1) + offset;
paginatorObjects.push({label: label});
}
sb.template.loadFrom(templateUrl, 'paginator').toHTML(paginatorObjects).appendTo(container, function(template) {
var pageNumber = template.obj.label;
if(pageNumber != page) {
sb.addEvent(template, 'click', function() {
getAppointments(pageNumber);
});
} else {
sb.dom.addClass(template, 'highlight');
}
});
if(offset + iterations < pages) {
var dots = document.createTextNode(' ... ');
container.appendChild(dots);
sb.template.loadFrom(templateUrl, 'paginator').toHTML({label: pages}).appendTo(container, function(template) {
sb.addEvent(template, 'click', function() {
getAppointments(pages);
});
});
}
var backBtn = paginator.getElementsByClass('icon back')[0];
var forwardBtn = paginator.getElementsByClass('icon forward')[0];
sb.removeEvent(backBtn, 'click');
sb.removeEvent(forwardBtn, 'click');
if(page - 1 > 0) {
sb.dom.removeClass(backBtn, 'hidden');
sb.addEvent(backBtn, 'click', function() {
getAppointments(page-1);
});
} else {
sb.dom.addClass(backBtn, 'hidden');
}
if(page + 1 <= pages) {
sb.dom.removeClass(forwardBtn, 'hidden');
sb.addEvent(forwardBtn, 'click', function() {
getAppointments(page+1);
});
} else {
sb.dom.addClass(forwardBtn, 'hidden');
}
} else {
sb.dom.addClass(paginator, 'hidden');
}
}
When getAppointments() is called from the buttons, I use AJAX to get the next pages results, then this pagination() function is called again from that function so everything gets reset. The variables that determine the amount to show per page and the current page number are global (to the container function) and are not shown in this code sample.
The logic behind this is fairly simple. The center is determined (in my case the max it shows at once is 5, so the center is 3) and then an offset is calculated based on the page number. Clicking 4 will adjust the start number +1, and 2 would adjust it -1.

Categories