user2024080
user2024080

Reputation: 5101

How to increment or dicrement from current index within the total

I am looping a number between 0 to total what i have. the thing is, it need to create from currentIndex and it should not more that total same way i need to dicreement the value from currentIndex but not less than 0.

I tried but nothing come handy. here is my try:

var total = 6;
var currentIndex = 3;
var num = 0;
function add(amount) {
   return num = (num + total - currentIndex + amount) % total + 1

}


$('a').click(function(e){
    var num = e.target.className == 'prev' ? -1 : 1;
    var result = add(num)+currentIndex;
    console.log(result);
});

Jsfiddle

Upvotes: 0

Views: 201

Answers (1)

depperm
depperm

Reputation: 10746

You need to think simpler, but you were on the right track:

var total = 6;
var currentIndex = 3;
var num = 0;
function add(amount) {
   currentIndex=((currentIndex+amount%total)+total)%total;
}


$('a').click(function(e){
    var num = e.target.className == 'prev' ? -1 : 1;
    add(num);
    console.log(currentIndex);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="prev">Prev</a>  <a href="#" class="next">Next</a>

This will loop between 0 and 5 inclusive.

Upvotes: 1

Related Questions