Home > Software engineering >  How to loop an addition and substraction on a base of 3 in query?
How to loop an addition and substraction on a base of 3 in query?

Time:11-21

I have a simpple Slider with 3 slides. Now everything works, but if I press more than 3 times in one direction I get "false" numbers. Mathemathically they are right, but Im aiming for this scenario:

If i click 4 times the button for previous slide, the counter of my numbers should be again 3, not -1. Any way to archive this?

  $( document ).ready(function() {
    
  var current =  $('.slider_number').data("hasso");
  var total = $('.slider_number').data("total")

  $('.slider_next').click(function(){
    current;
  console.log(current)
  $(".slider_number").text(current)
});
  $('.slider_prev').click(function(){
  --current;
  console.log(current)
}                                     
);
 });

CodePudding user response:

Use the circular index formula (i % n n) % n where n is the length of the array (4 in your case).

use:

current = (current 1 % total   total) % total;

to move forward;

and

current = (current-1 % total   total) % total;

to move backwards.

current will always be a valid index.

  • Related