AnchovyLegend AnchovyLegend - 1 year ago 102
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]);
$('.catalog-img-container').attr("src", javascript_array[++index%arrayLength]);
$('.catalog-img-container').attr("src", javascript_array[--index]);

I appreciate any help with

Many thank in advance.

Answer Source

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

    if (--index < 0) index = arrayLength - 1;
    $('.catalog-img-container').attr("src", javascript_array[index%arrayLength]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download