Ron Ron - 6 months ago 17
Javascript Question

paginating arrays javascript by click

i have two links:

<a href="#" id="theone" data-do="1" class="loopit">loop it</a>
<a href="#" id="thetwo" data-do="2" class="loopit">loop it 2</a>


then on click i fire a function that loops an array. it works great when there is one loop but mess up when there are more, in this example two.:

var jsonArray = ["one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve"];
var jsonArray2 = ["january","fabruar","march","april","may","june","july","august","september","october","november","december"];
var current_group = 0;
var group_size= 5;
var group_size2= 2;
var theskip;
function cycleArray(thearr,thesize) {
var current_items = thearr.slice(current_group, current_group + thesize);
var skip = current_group += thesize;

console.log(current_items);
console.log(skip);

if(current_group > thearr.length) {
console.log("no more");
/* then we stop! no more items, so maybe disable button etc */
}
}

$(".loopit").on("click", function(e){
e.preventDefault();
var theclicked = $(this).attr("data-do");

//alert(theclicked);
if (theclicked == "1") {
cycleArray(jsonArray,group_size);
}else{
cycleArray(jsonArray2,group_size2);
}

});


so the issue is the skip part. it saves the last one, which is crucial, BUT if i pressed the first link i do get the first 5, but then if i press the second link, i get from the right array two results (great) BUT obviously it start from the fifth, and not the start.

how can i do it?

best regards

Answer

The problem is that you are keeping track of current_group with the same variable for both arrays. So when you click on the first button with size 5 the current_group var gets set to 5 and so the next call to cycleArray for arrayJson2 starts at position 5.

In JavaScript you can treat arrays like objects and assign themm properties so a better solution would be to keep track of current_group like this:

var jsonArray = ["one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve"];
var jsonArray2 = ["january","fabruar","march","april","may","june","july","august","september","october","november","december"];

// Here initialize them with zero
jsonArray2.current_group = 0;
jsonArray.current_group = 0;

var current_group = 0;
var group_size= 5;
var group_size2= 2;
var theskip;
function cycleArray(thearr,thesize) {
// now you can sefely access the property coresponding the correct array
var current_items = thearr.slice(thearr.current_group, thearr.current_group + thesize);
var skip = thearr.current_group += thesize;

console.log(current_items);
console.log(skip);

if(thearr.current_group > thearr.length) { 
    console.log("no more");
/* then we stop! no more items, so maybe disable button etc */ 
}
}
Comments