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]);
});
});
$(document).ready(function(){
var currentPos = 0;
$("#next").click(function()
{
currentPos++;
printThings(currentPos);
});
});
function printThings(maxLength)
{
maxLength = maxLength > stuff.length ? stuff.length : maxLength;
var stuff =["house","garden","sea","cat"];
for (var i=0; i<maxLength;i++)
{
console.log(stuff[i]);
}
}
I wanted to cycle in the opposite direction:
$("#prev").on('click', function(){
stuff.reverse();
i = (i+1)%stuff.length;
console.log(stuff[i]);
});
It works but it skips one value...
I would add a text box to the form. Then, on your #next click function loop the array. While looping compare the array value to what is in the text box. When you get a match - change the value of the text box to the next array value in the loop, then exit the loop.