javascriptjquerypaginationsites

pagination wrong progress of numbers


This is my Code:

var pages = Math.ceil(allItems / itemsPerPage);
var pagesArray = [];
for(var i = 0; i < pages; i++){
    pagesArray.push(i);
}
var show = 3;
var offset = pageCounter + show;
var showPages = pagesArray.slice(pageCounter, offset);
for(var h = 0; h < showPages.length; h++){
    if(pageCounter == showPages[h]){
        selectedPageClass = 'selected';
    }else{
        selectedPageClass = '';
    }
    $(".pagination").append("<a href='#' class='" + selectedPageClass +"'>" + showPages[h] + "</a>");
}   

My Problem now is: if I have this array ["1","2","3","4","5"]

First Step when I am on page "0" it should be :

1(selected) 2 3

this works. but than it goes on like this:

2(selected) 3 4

3(selected) 4 5

4(selected) 5

5(selected)

But what I want is this:

1(selected) 2 3

2(selected) 3 4

3(selected) 4 5

3 4(selected) 5

3 4 5(selected)


Solution

  • http://codepen.io/anon/pen/JbBYva

    You can update the variables on the top, the pageCounter is 0-based.

    //editable variables
    var pages = 5;
    var pageCounter = 0;
    var show = 3;
    
    //calculation 
    var pagesArray = [];
    for(var i = 1; i <= pages; i++){
        pagesArray.push(i);
    }
    var offset = pageCounter + show;
    var showPages = pagesArray.slice(Math.min(pages - show, pageCounter), offset);
    for(var h = 0; h < showPages.length; h++){
        if(pageCounter + 1 == showPages[h]){
            selectedPageClass = 'selected';
        }else{
            selectedPageClass = '';
        }
        $(".pagination").append("<a href='#' class='" + selectedPageClass +"'>" + showPages[h] + "</a>");
    }