user4500458
user4500458

Reputation:

Cycling through an array in JavaScript using JQuery

I come from a Ruby background, so forgive me if this is an amateurish question. I have a color selector, where a paragraph changes its text to match a color

<button class="btn btn-primary">Please Select a Color</button>
<p class="color-select"></p>

JavaScript/Jquery

var colors = ["red", "green", "yellow", "red", "purple"];

$(document).ready(function() {
  $("button").click(function() {
    $(".color-select").html(colors[Math.floor(Math.random() * 5)]);
  });
});

As you can see, I am well aware of how to select a random element in JavaScript. In Ruby, it would be even simpler

colors.sample

But what I would like to do is to cycle through the colors. If I click on the button, the text will read red. If I click on it again, the text will read green. After the text is purple, it will cycle back to red and keep cycling through the various colors.

One insane, wacky idea I have is something like the following.

var i = 0;
while (i < colors.length) {
  $('.color-select').html(colors[i]);
  i++;
  if (i == 4) {
    i = 0
  }
}

That will probably not work because the text is changing without clicking a button. Any ideas?

Here is a fiddle

http://jsfiddle.net/c7ea2m6f/

Upvotes: 1

Views: 126

Answers (2)

Mritunjay
Mritunjay

Reputation: 25882

This will work for you.

var colors = ["red", "green", "yellow", "red", "purple"];

$(document).ready(function () {
    var i = 0;
    $("button").click(function () {
        $(".color-select").html(colors[i]);
        i++;
        i = i % 5;
    });
});

DEMO

Upvotes: 7

Darkmouse
Darkmouse

Reputation: 1939

I updated your fiddle

http://jsfiddle.net/c7ea2m6f/4/

var colors = ["red", "green", "yellow", "blue", "purple"];

$(document).ready(function() {
    var i = 0;
  $("button").click(function() {
      if (i < colors.length) {
    $(".color-select").html(colors[i]);
     i++;
          if (i == 5) {
              i = 0;
          }
      }
  });
});

Use an if loop instead of a while loop.

Edit: You mentioned red twice in your colors array. To avoid confusion, I changed it to something different.

Upvotes: 0

Related Questions