Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep an index within bounds and wrap around

Tags:

javascript

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) ?

like image 894
Benjamin Crouzier Avatar asked Dec 20 '22 04:12

Benjamin Crouzier


1 Answers

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);
    ...
like image 103
Benjamin Crouzier Avatar answered Dec 30 '22 03:12

Benjamin Crouzier