2

HOW TO MODIFY THIS SCRIPT AND PREVENT .test-box elements from having same color as siblings provided that they are 4 .test-boxes

var colors = [
    "rgb(100, 50, 100)",
    "rgb(200, 100, 200)",
    "rgb(150, 75, 150)",
    "rgb(230, 80, 230)",
];

function colorsFunction() {
    // Get all the elements that use the "view" class but do it using querySelectorAll
    var divs = Array.prototype.slice.call(document.querySelectorAll(".test-box"));

    // Loop through the array of divs
    divs.forEach(function(div){
        // Set the background color of each div
        div.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
    });

}
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
JOHNS
  • 37
  • 4

2 Answers2

2

Shuffle the array then use the index provided by forEach instead of a random one:

function colorsFunction() {
    var divs = Array.prototype.slice.call(document.querySelectorAll(".test-box"));

    // You can use any shuffling method you like, for simplicity we are using this less pwerful one. To be honnest I don't know why you want to shuffle the array anyway, can't you just use the colors as they are in the array?
    colors.sort(function(a, b) { return Math.random() - 0.5; });

    // use the index i provided by forEach
    divs.forEach(function(div, i) {
        div.style.backgroundColor = colors[i];
    });

}

Note: The shuffling algorithm used in the code above is not a very good one but it is much concise so I used it. If you want a much better one then check this other SO question. I used it because I'm still not convinced that you need to shuffle the array at all.

ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
2

Shuffle the array instead

var colors = [
  "rgb(100, 50, 100)",
  "rgb(200, 100, 200)",
  "rgb(150, 75, 150)",
  "rgb(230, 80, 230)",
];

function colorsFunction() {
  colors.sort(function() { return Math.random() - 0.5 })
  var divs = Array.prototype.slice.call(document.querySelectorAll(".test-box"));

  // Loop through the array of divs
  divs.forEach(function(div, i) {
    // Set the background color of each div
    div.style.backgroundColor = colors[i];
  });

}

colorsFunction()
.test-box {
  height: 50px
}
<button onclick="colorsFunction()">Change colors</button>
<div class="test-box"></div>
<div class="test-box"></div>
<div class="test-box"></div>
<div class="test-box"></div>
charlietfl
  • 170,828
  • 13
  • 121
  • 150