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