I have a button that iterates through an array on click and displays the contents of the array. When I get to the end of the array, I would like to set the counter back to the beginning. Here is my code so far:
HTML:
<div id="likes">
<span class="figure">
</span>
</div>
<button type="button" id="like" >Like</button>
JavaScript:
var clicks = 0; $("#like").click(function(){ clicks++;
$('.figure').html(clicks);});
working demo: http://jsfiddle.net/nTmu7/2/
Use the Reminder operator (AKA: Modulus) %
to loop your array
counter = (counter + 1) % array.length;
Example:
var array = ["One", "Two", "Three"];
var counter = 0;
$("#like").click(function(){
$('#likes').text( array[counter] );
counter = ++counter % array.length;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="like">LOOP ARRAY</button>
<div id="likes"></div>
Always good to re-read: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators
Modulus the counter by the size of the array. I.e. I % array.length will get you back to 0. If I equals the length. I normally have an if statement.
Like
if(I == array.length){
I %= array.length;
}
You can simply use modulo (%
).
Taking the modulo by length of an array guarantees that you never excced it:
var ind = 0;
var val = ['a', 'b', 'c'];
$("button").on('click', function() {
ind = (ind + 1) % val.length; // or "ind++; ind %= val.length;"
$(this).text(val[ind]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>a</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With