Anonymous Anonymous - 2 months ago 9
HTML Question

How to change row colors in a loop?

I'm trying to change some divs background colors. Now I know how to change even and odds elements background colors. How to change the background in a JavaScript loop using the next pattern: one row blue, two rows red, one row blue, two rows red, and so on?

My code:



var count = 0;
$('#content .row').each(function () {
if(count%2 == 0){
$(this).css('background', '#F00');
}else{
$(this).css('background', '#3875D9');
}
count++;
});

.row{
display: inline-block;
width: 100%;
color: #fff;
text-align: center;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='content'>
<div class='row'>row</div>
<div class='row'>row</div>
<div class='row'>row</div>
<div class='row'>row</div>
<div class='row'>row</div>
<div class='row'>row</div>
<div class='row'>row</div>
</div>





UPDATE:

After the answers, I saw that I didn't even knew what I was trying to achieve, so I'm going to post and image here. The question is almost the same. I will let the image explain what I am trying to do:

enter image description here

Answer

Simply use % 3 instead of % 2 and adjust the condition accordingly:

Edit

After the question was edited, I tried to find a solution and found this, which is a bit of a hack:

  • make rows width: 50%; float: left to fit two of them in one row
  • modify a little the logic of applying colors

$('#content .row').each(function (index) {  
    if(index % 4 == 0 || index % 4 == 3){
        $(this).css('background', '#3875D9');       
    }else{
        $(this).css('background', '#F00');              
    }
});
.row{
  display: inline-block;
  width: 50%;
float:left;
  color: #fff;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='content'>
  <div class='row'>row</div>
  <div class='row'>row</div>
  <div class='row'>row</div>
  <div class='row'>row</div>
  <div class='row'>row</div>
  <div class='row'>row</div>
  <div class='row'>row</div>
</div>