title: Keep an index within bounds and wrap around
body: <p>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.</p>
  
  <p>My code looks like this:</p>
  
  <pre><code>$('#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;
  });
  </code></pre>
  
  <p>And it fails miserably because -6 % 36 is -6 and not 30. I could handle it with if <code>(index &lt; 0) ...</code> but I would prefer a condition with a modulo that best capture the wrapping behavior.</p>
  
  <p>How can I get this to wrap around (see 2nd line) ?</p>