tweb
tweb

Reputation: 143

Jquery change colors with recursion

Here is jsfiddle of raw code and the result should be like this

<div class="wrapper">
 <div class="row">
  <div class="col red">R</div>
  <div class="col blue">B</div>
  <div class="col green">G</div>
  <div class="col orange">O</div>
 </div>
</div>

The mission is: Last color of previous row should be the first in next row and first color from previuos row should be the second in next row.

I think that I have to use loop and recursion but I don't have enough knowledge to do this.

Thanks in advance :)

Upvotes: 0

Views: 94

Answers (1)

Geeky
Geeky

Reputation: 7498

You can run through the for loop and do something like this

check this snippet

//last color of previous row should be first in next row

//first color from previous row should be second in next row
var colors = ['red', 'blue', 'green', 'orange'];
$(document).ready(function() {
  var rows = $('.row');
  rows.each(function(row) {
    var index = $(this).index();
    var prevRow;
    if (index > 0)
      prevRow = $(this).prev();
    colorColumns($(this).find('.col'), prevRow);
  });
});

function colorColumns(cols, prevRow) {
  var index = 0;
  // alert("hi");
  cols.each(function(col) {
    var colIndex = $(this).index();

    if (prevRow) {
      var cols = prevRow.find('.col').length;
      var totalCols = cols - 1;

      var currentIndex = ((colIndex + totalCols) % cols);
      var prevRowColor = $(prevRow).find('.col').eq(currentIndex);
      var classes = prevRowColor.attr('class');
      var classArr = classes.split(" ");

      $(this).addClass(classArr[1]);

    } else {

      $(this).addClass(colors[colIndex]);
    }
  });

}
.row {
  display: flex;
}
.row .col {
  width: 20px;
  height: 20px;
  border-radius: 100%;
  text-align: center;
}
.red {
  background: red;
}
.orange {
  background: orange;
}
.blue {
  background: blue;
}
.green {
  background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="row">
    <div class="col">R</div>
    <div class="col">B</div>
    <div class="col">G</div>
    <div class="col">O</div>
  </div>
  <div class="row">
    <div class="col">R</div>
    <div class="col">B</div>
    <div class="col">G</div>
    <div class="col">О</div>
  </div>
  <div class="row">
    <div class="col">R</div>
    <div class="col">B</div>
    <div class="col">G</div>
    <div class="col">O</div>
  </div>

Hope it helps

Upvotes: 1

Related Questions