I am doing a little carousel with a pager. The carousel displays elements 6 by 6 and I have 36 elements to display. I have a next and previous button. The first elements displayed are [0, 6]. If I press the previous button and there is no previous elements (eg I am on the first page), it should wrap around and go to the end. The same applies for the last elements and the next button.
My code looks like this:
$('#img_prev').click(function (e) {
# change this line so it wraps around
imgIndex = (imgIndex - 6) % 36;
alert(imgIndex)
refreshImages(imgIndex);
e.preventDefault();
return false;
});
$('#img_next').click(function (e) {
imgIndex = (imgIndex + 6) % 36;
refreshImages(imgIndex);
e.preventDefault();
return false;
});
And it fails miserably because -6 % 36 is -6 and not 30. I could handle it with if (index < 0) ...
but I would prefer a condition with a modulo that best capture the wrapping behavior.
How can I get this to wrap around (see 2nd line) ?
One possible solution would be with this answer:
function mod(x, m) {
return (x%m + m)%m;
}
$('#img_prev').click(function (e) {
# this line has been changed, now it wraps around
imgIndex = mod(imgIndex - 6, 36);
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With