kathrynm kathrynm - 11 days ago 9
Javascript Question

Rotate through Array every second

I have a simple rainbow clock, the idea is that every second that passes the background colors of the stripes change to the next color in the array. I'm trying to get the value of seconds to offset the array and then wrap around to the beginning.

for example:

var seconds = 0;

var colors = ['red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'violet', 'pink'];


would become, when I iterate:

var seconds = 1;

var colors = ['pink', 'red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'violet'];


I'm currently using this:

$('.color').each(function setColors(i) {
$(this).css('background', colors[i]);
});


But I'm trying to do something like this:

var seconds = time.getSeconds();

$('.color').each(function setColors(i) {
$(this).css('background', colors[i + seconds]);
});


Here's my fiddle

Thank you in advance for any help you may have :)


  • K


Answer

You can pop a color from the end of the array and add it to the start of the array using:

colors.unshift(colors.pop());

See demo below:

// get seconds
setInterval(getSeconds, 1000);

// set colors
var colors = ['red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'violet', 'pink'];

// initalize colors
  $('.color').each(function setColors(i) {
    $(this).css('background', colors[i]);
  });

function getSeconds() {
  var time = new Date($.now());
  var seconds = time.getSeconds();
  $('#seconds').text(seconds);

  $('.color').each(function setColors(i) {
    $(this).css('background', colors[i]);
  });
  
  // shift the colors
  colors.unshift(colors.pop());
};
body {
  margin: 0;
  padding: 0;
}
#seconds {
  font-size: 3em;
  position: absolute;
  margin: auto;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  height: 1em;
  width: 3em;
  text-align: center;
  color: #FFF;
  font-family: sans-serif;
  z-index: 100;
}
.color {
  position: relative;
  height: 12.5vh;
  width: 100vw;
  background: #456;
  transition: all 1s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="seconds">seconds</div>

<div class="color"></div>
<div class="color"></div>
<div class="color"></div>
<div class="color"></div>
<div class="color"></div>
<div class="color"></div>
<div class="color"></div>