AnchovyLegend AnchovyLegend - 10 days ago 8
Javascript Question

Using mod to wrap around

Assume the array has a length of 1000. I am trying to create a simple way to traverse the image paths stored in the array without going out of bounds. The method below handles the wrap around using modulus well when it comes to clicking the 'next' button to increment array index, but not when I have to decrement and deduct one from the index (when the user clicks the previous button).

Basically what I am trying to do is:

998 -> click next -> 999
999 -> click next -> 0
0 -> click previous -> 999


My Javacript

var index = 0;

$('.catalog-img-container').attr("src", javascript_array[index]);
$(".next").click(function(){
$('.catalog-img-container').attr("src", javascript_array[++index%arrayLength]);
});
$(".previous").click(function(){
$('.catalog-img-container').attr("src", javascript_array[--index]);
alert(index);


I appreciate any help with

Many thank in advance.

Answer

There might be a more elegant way around this, but this is simple:

$(".previous").click(function(){
    if (--index < 0) index = arrayLength - 1;
    $('.catalog-img-container').attr("src", javascript_array[index%arrayLength]);
});