Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create pagination like behavior for an array in javascript

Tags:

arrays

jquery

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?

like image 427
chell Avatar asked Dec 15 '11 10:12

chell


People also ask

How can I paginate an array of objects in JavaScript?

To paginate a JavaScript array, we can use the JavaScript array's slice method. For instance, we write: const paginate = (array, pageSize, pageNumber) => { return array. slice((pageNumber - 1) * pageSize, pageNumber * pageSize); } console.

How can I use pagination in JavaScript?

JavaScript Pagination concept is applied for moving among the pages with First, Next, Previous and Last buttons or links. Pagination's main motto is to move among the content immediately by clicking links or buttons. Pagination has multiple links or buttons provided for access First, Next, Previous and Last content.

How do you make an array of numbers in JavaScript?

var rank = new Array(1, 2, 3, 4); The Array parameter is a list of strings or integers. When you specify a single numeric parameter with the Array constructor, you specify the initial length of the array.

Can you put numbers in an array JavaScript?

Use the for Loop to Sum an Array in a JavaScript Array We can use it to add all the numbers in an array and store it in a variable. Copy const array = [1, 2, 3, 4]; let sum = 0; for (let i = 0; i < array. length; i++) { sum += array[i]; } console.


2 Answers

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.

like image 77
kubetz Avatar answered Sep 20 '22 04:09

kubetz


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

like image 41
Pranesh Janarthanan Avatar answered Sep 19 '22 04:09

Pranesh Janarthanan