I have a photo gallery that includes images that will be continuously uploaded. The PHP array has been converted/encoded to a JSON array so that I can manipulate the data with JavaScript.
Ideally, I would like to click a button ("Next Set" in the CodePen example) and load the next set (of 2) thumbnail images. This is in an effort to not load all of the images at once, which could be hundreds.
Problem: I cannot figure out how to dynamically slice the array on click (next 5 images). I can of course load, say, 2 at a time:
myArray.slice(0,2);
myArray.slice(3,5);
However, this will not work because images will be continuously added to the gallery. Furthermore, I would have to have too many sets of the above to keep slicing 5 out at a time.
I have tried:
- Splitting the array into smaller arrays
forloops and$.eachloops
I essentially need to be able to move the start and end index of the slice by (for example) 2 on click. Right now it just keeps slicing the same two images because the slicing is not dynamic.
Here is my CodePen
.slice(index, index + 5); index += 5;splicewhich cut items out from the array! Every time you call.splice(0, 2)you'll get different elements because the previous ones have been cut out from the original array!spliceshould always start with 0 (.splice(0, amount))!.shiftcut only one item from the begining of the array, to use it you need a loop to cut as many as you want! Using.splice(0, amount)will cutamountof items from the begining so no loop is needed! If you'll need to loop through the result array of thespliceing then useshift. If you'll use the return array as a whole then use.splice. One thing to mention is thatspliceis safer because([1, 2].splice(0, 10000) === [1, 2]), inshiftversion you'll have to check if there still element in the array to see if you'll continue or not(otherwise undefineds ar returned)!spliceyou could useforEachlike this:array.splice(0, amount).forEach(function(img) { /* use img here */});!pushis slightly better in performance!