I am trying to get into JQuery but am struggling a bit around.
What I'm trying to do is go through an array one click at a time so that each time I click on the "next" button a new item is presented.
Let's take a look at the following code:
$(document).ready(function(){
var stuff =["house","garden","sea","cat"];
for (var i=0; i<stuff.length;i++)
{
console.log(stuff[i]);
}
});
Now how I was thinking something like creating a while loop with i
$("#next").on('click', function(){i++;});
But this somehow doesn't work. Anyone able to explain to me how to do this in a relatively simple way?
When you run through your loop with the for statement, it does so immediately and not in response to an event.
Instead, you want to step through the array with each click. To do so, you need to define a counter outside your click function and increment (or reset, if you've reached the end of the array) with each click.
Here is some sample code:
$(function () { // this is a shortcut for document ready
var stuff = ['house', 'garden', 'sea', 'cat'],
counter = 0;
console.log(stuff[counter]); // your initial value
// the next line, of course, assumes you have an element with id="next"
$('#next').click(function () {
counter = (counter + 1) % stuff.length; // increment your counter
// the modulus (%) operator resets the counter to 0
// when it reaches the length of the array
console.log(stuff[counter]); // the new incremented value
});
});
I hope this helps!
Simply keep a counter outside your callback and increment it at each click :
$(document).ready(function(){
var i = 0;
var stuff =["house","garden","sea","cat"];
$("#next").on('click' function(){
i = (i+1)%stuff.length;
console.log(stuff[i]);
});
});
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