2

I am trying to figure out pagination based on this solution here: https://stackoverflow.com/a/44844/3214545

I have never really done complex logic so I am having difficulty with it. This is my code:

var allPages = 50;
var current = 16;
var pageLinks = [];

function updatePageLinks(current, allPages) {
            if (current > 1) {
                pageLinks.push('<', 1);
            }
            if (current > 2) {
                pageLinks.push('...');

                if (current == allPages && allPages > 3) {
                    pageLinks.push((current - 2), (current - 1));
                }
            }
            if (current != 1 && current != allPages) {
                pageLinks.push(current);
            }
            if (current < allPages - 1) {
                pageLinks.push((current + 1), (current + 2), '...');

                if (current == 1 && allPages > 3) {
                    pageLinks.push((current + 2), '...');
                }
            }
            pageLinks.push(allPages);                

            if (current < allPages) {
                pageLinks.push('>');
            }
            $('#pages').append("<a href='#'>  " + pageLinks + '</a>');
        }

I will be loading the page numbers from another part of the application but for the moment I just set the numbers so I can test different edge cases. Above the current page is 16 and total pages is 50 So I want the output to be something like:

<1 2 ... 15 16 17 ... 49 50>

where the first 2 and last 2 pages are always shown and the current page + and - 1

Examples of Problems:

  1. if the current page is set to 1, the output is 2,3,...,50>
  2. if the current page is 2, the output is <,1,2,3,5,> doesn't print 4

  3. if the current page is set to 2 and total is 50, the output is <,1,2,3,10>

  4. if the current page is set to 5, the output is <,1,...,5,6,50>

Can anyone help me?

Community
  • 1
  • 1
user3214545
  • 2,103
  • 3
  • 20
  • 26

1 Answers1

4

I updated your code using the last algorithm in the question you linked

updatePageLinks(16, 50);

function print(value) {
    $('#pages').append("<a href='#'>"+value+"</a> ");
}

function updatePageLinks(current, allPages) {
    if(allPages==0) return;
    if(current>1)print("<");
    print(1);
    if(current>2) {
        print("...");
        if(current===allPages&&allPages>3)
            print(current-2);
        print(current-1);
    }
    if(current!=1&&current!=allPages)
        print(current);
    if(current<allPages-1) {
        print(current+1);
        if(current==1&&allPages>3)
            print(current+2);
        print("...");
    }
    print(allPages);
    if(current<allPages)
        print(">");
}

JSFiddle

Community
  • 1
  • 1
Danny
  • 7,368
  • 8
  • 46
  • 70