chell
chell

Reputation: 7866

How to create pagination like behavior for an array in javascript

In my application after getting my application Authorized by Facebook I get all their friends info which is returned in an array.

I sort this array in order of the friends whose birthday is closest to the current date.(code not shown for this)

I want to display the information for 20 friends at a time as some users may have hundreds of friends.

Currently I am putting all of the friends on the page at one time.

Here is the code I was using to loop through the entire array and put the info on the page

$.each(json.data,function(i,fb){

                  var pic_url = "http://graph.facebook.com/"+fb.id+"/picture";
                  json_details = {name: fb.name, provider_user_id: fb.id, birthday: fb.birthday, provider_name : 'Facebook' }; 
                  var celebrant_details = escape(JSON.stringify(json_details) );
                  html += "<form id='new_celebration"+fb.id+"' method='post' action='/celebrations' accept-charset='UTF-8'>";
                  html += "<input type='hidden' id='friend' value='"+celebrant_details +"'  name='celebrant_details'  />"
                  html += "<input type='hidden' id='manager' value='"+manager_details +"'  name='manager_details' />"

                  html += "<li>" + fb.name + "</li>";
                  if(fb.birthday != null){  html += "<li>" + fb.birthday + "</li>"; } //don't show if don't have a birthday
                  html += "<li><img src="+pic_url+" /></li>";       
                  html += "<input class='button-mini-subtle submit' type='submit' value='select' alt='select'  >";    
                  html += "</form>";

                });//.each loop

I am a NOOB so would appreciate some guidance.

I want to give the users a button they can click to display more users from the array. So I know I need to create some kind of a function call and I need to know where I am in the array.

How can I get this kind of behavior?

Upvotes: 7

Views: 18453

Answers (2)

Pranesh Janarthanan
Pranesh Janarthanan

Reputation: 1194

Answer Prepared from Source: W3Schools and JSBin and Kubetz Sol

  <!DOCTYPE html>
        <html>
        <body>
            <p>Array Based Pagination</p>
            <button onclick="First()">First</button>
            <button onclick="Previous()">Previous</button>
            <button onclick="Next()">Next</button>
            <button onclick="Last()">Last</button>
            <p id="demo"></p>
            <br />
            <p id="page"></p>
            <br />
            <p id="info"></p>
            <script>
                var arr = [];
                var currentPage = 1;
                var pageSize = 5;
                var skip = 0;
                var totalCount = 0;
                var totalPage = 0;
                for (var i = 1; i <= 100; i++) {
                    arr.push(i);
                }
                myFunction();

                function First() {
                    currentPage = 1;
                    skip = 0;
                    myFunction();
                }

                function Next() {
                    if (currentPage < totalPage) currentPage++;
                    skip = pageSize * (currentPage - 1);
                    myFunction();
                }

                function Previous() {
                    if (currentPage > 1) currentPage--;
                    skip = pageSize * (currentPage - 1);
                    myFunction();
                }

                function Last() {
                    currentPage = totalPage;
                    skip = pageSize * (currentPage - 1);
                    myFunction();
                }

                function myFunction() {
                    totalCount = arr.length;
                    totalPage = Math.ceil(totalCount / pageSize);
                    var citrus = arr.slice(skip, skip + pageSize);
                    document.getElementById("info").innerHTML = "skip: " + skip + ", CP: " + currentPage + ", pageSize: " + pageSize;
                    document.getElementById("demo").innerHTML = citrus;
                    document.getElementById("page").innerHTML = "Page Info: " + currentPage + "/" + totalPage;
                }
            </script>

        </body>
        </html>

My Above Code Demo @ W3Schools

Upvotes: 1

kubetz
kubetz

Reputation: 8556

You can use a extra index variable that will hold current index in your array or have the index stored as the jQuery .data(). Then you can use Array.slice() to get the subarray.

Here is the simplified example using .data(). You have to adapt it to your data structure and required HTML output - that was not your question :).

// display our initial list
displayNext();

$("#next").click(function() {
  // display next elements
  displayNext();
});

function displayNext() {
  // get the list element
  var list = $('#list');

  // get index stored as a data on the list, if it doesn't exist then assign 0
  var index = list.data('index') % arr.length || 0;

  // save next index - for next call
  list.data('index', index + 20);

  // 1) get 20 elements from array - starting from index, using Array.slice()
  // 2) map them to array of li strings
  // 3) join the array into a single string and set it as a HTML content of list
  list.html($.map(arr.slice(index, index + 20), function(val) {
    return '<li id=' + val.id + '>' + val.name + '</li>';
  }).join(''));
}

HERE is the code.

Upvotes: 10

Related Questions