Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cycle through an array on click

Tags:

javascript

I am wondering how to cycle through the values in an array on click? When the last value of the array is displayed, then the next click should display the first value of the array again.

I think that I am close, however when I get to the last value of the array I have to click twice before it displays the first value again.

Here is my JavaScript:

var myArray = ["red", "yellow", "green"];
var myIndex = 1;
var print = document.getElementById('print');

print.innerHTML = myArray[0]; //Print first value of array right away.

function nextElement() {
  if (myIndex < myArray.length) {
     print.innerHTML = myArray[myIndex];
     myIndex++;
  }
  else {
     myIndex = 0;   
  }
};

Here is my HTML:

<p>The color is <span id="print"></span>.</p> 

<a id="click" href="#" onclick="nextElement();">Click</a>

Here's a fiddle if that is helpful:

http://jsfiddle.net/jBJ3B/

like image 413
Mdd Avatar asked Sep 07 '25 16:09

Mdd


2 Answers

You could use the modulo operator like this:

function nextElement() {
  print.innerHTML = myArray[myIndex];
  myIndex = (myIndex+1)%(myArray.length);
  }
};

See: http://jsfiddle.net/jBJ3B/3/

Even more extreme is (as zdyn has written):

function nextElement() {
   print.innerHTML = myArray[myIndex++%myArray.length];
};

See: http://jsfiddle.net/jBJ3B/5/

like image 51
Menelaos Avatar answered Sep 09 '25 06:09

Menelaos


As concise as I could get it:

function nextElement() {
  print.innerHTML = myArray[myIndex++ % myArray.length]
}
like image 21
zdyn Avatar answered Sep 09 '25 07:09

zdyn