j1mmy j1mmy - 3 years ago 179
HTML Question

Shifting forward in an array when iterating over elements

I have repeating elements (section) on a page. I want to iterate the background colors of the elements between three colors that are held in a array. And within some of those elements I have text (p) that I want to iterate through those same colors, except I want it to be the next color in the array as the background.

So if I have an array that looks like ["111111", "222222", "333333"], I want the background color of the first section to be #111111 and the color of the first p to be #222222. Also there are more elements on the page than there are items in the array so we need to loop back through the array. The page when complete should look like:

<body>
<section style="background-color: #111111;">
<p style="color: #222222;">foo bar</p>
</section>
<section" style="background-color: #222222;">
<p style="color: #333333;">foo bar</p>
</section>
<section style="background-color: #333333;">
<!--no p in this one-->
</section>
<section style="background-color: #111111;">
<p style="color: #222222;">foo bar</p>
</section>
</body>


I have the background-color part done but I can't figure out how to shift to the next item in the array and start over at the first item when necessary.

var bgColors = ["111111", "222222", "333333"];
$('section').each(function(i) {
var bgColor = bgColors[i % bgColors.length];
$(this).css('background-color', '#'+bgColor);
// How to do text color???
$(this).find("p").css('color', ???);
});


The script should be flexible so you can add and change colors. Thanks.

EDIT: I realized I left out an important point which is that not every section has a p so you can't just iterate through them each independently. Also due to a c&p mishap my html didn't match my JS. Apologies.

Answer Source

Just use i+1 for the modulo for the foreground

It is the same logic you already apply for the bgColor, you just need to go one more for the foreground

var bgColors = ["red", "green", "blue", "yellow"];
$(function() {
  $('.section').each(function(i) {
    var bgColor = bgColors[i % bgColors.length];
    var fgColor = bgColors[(i + 1) % bgColors.length];
    $(this).css('background-color',  bgColor);
    $(this).find(".text").css('color', fgColor);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="section">
  <div class="text">foo bar</div>
</div>
<div class="section">
  <div class="text">foo bar</div>
</div>
<div class="section">
  <div class="text">foo bar</div>
</div>
<div class="section">
  <div class="text">foo bar</div>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download