Using mod to wrap around
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]);
});
Since --index%arrayLength
doesn't work, just add the length of the array prior to taking the modulo:
index = (index+arrayLength-1) % arrayLength
You could also do
(index+=arrayLength-1)%arrayLength
but this will lead to index
getting very large, possibly out of range over enough time.
You can also use a handy object for it.
var Cursor = function (array) {
var idx = 0;
this.prev = function () {
idx = (!!idx ? idx : array.length) - 1;
return array[idx];
};
this.current = function () {
return array[idx];
};
this.next = function () {
idx = (idx + 1) % array.length;
return array[idx];
};
return this;
};
For example,
var $container = $(".catalog-img-container");
var cursor = new Cursor(javascript_array);
$container.attr("src", cursor.current());
$(".next").click(function(){
$container.attr("src", cursor.next());
});
$(".previous").click(function(){
$container.attr("src", cursor.prev());
});