Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a clever way using Math functions to handle pagination with rotation?

I guess everybody has had this scenario when implementing a pagination: You are on the first or last element and the user goes forth or back and starts a new rotation. My naive implementation is this:

let total = 3;
let index = 0;

const goto = (where) => {
  index += where === 'prev' ? -1 : 1;

  if (index < 0) index = total - 1;
  if (index >= total) index = 0;
  
  document.getElementById('b').textContent = index;
}

document.getElementById('a').addEventListener('click', () => goto('prev'));
document.getElementById('c').addEventListener('click', () => goto('next'));
<button id="a" type="button">Prev</button>
<span id="b">0</span>
<button id="c" type="button">Next</button>

Is there a way to simplify these cumbersome if-clauses using some clever math? Also, is a possible alternative also easy to read and to follow for somebody else reading the code?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could take the offsets of prev and next as variable and use the remainder to get a value between zero (with) and total (without).

const
    prev = -1,
    next = 1,
    total = 3;

let index = 0;

const goto = (where) => {
    index += total + where; // prevent negative value
    index %= total;         // get interval

    document.getElementById('b').textContent = index;
};

document.getElementById('a').addEventListener('click', () => goto(prev));
document.getElementById('c').addEventListener('click', () => goto(next));
<button id="a" type="button">Prev</button>
<span id="b">0</span>
<button id="c" type="button">Next</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading