Random color on different div’s

Tags: , ,



I have 3 div’s

<div id="box1"></div>
<div id="box2"></div>
<div id="box3"></div>
<button>Enter</button>

I want to give it a random color using javascript controlled css. Like this:

var randomColor = Math.ceil(Math.random() * 3);
var color = "";
//Accessing the divs
var box1 = document.querySelector("#box1");
var box2 = document.querySelector("#box2");
var box3 = document.querySelector("#box3");

//Event
var button = document.querySelector("button");
button.addEventListener("click", randomize, false);
button.style.cursor = "pointer";

function render(){
    box1.style.background = color;
    box2.style.background = color;
    box3.style.background = color;
}

function randomize(randomColor){
    switch(randomColor){
        case 1:
        color = "red";
        break;
        case 2:
        color = "blue";
        break;
        case 3:
        color = "green";
        break;
    }
render();
}

The problem is that, it’s giving me the same color in every div. Any idea how can i solve this, I want to do it pure javascript and css no jquery if possible. Im still learning javascript. Thank you..

Answer

You could use classes instead of ids and simplify your code to following.

// You could easily add more colors to this array.
var colors = ['red', 'blue', 'green', 'teal', 'rosybrown', 'tan', 'plum', 'saddlebrown'];
var boxes = document.querySelectorAll(".box");
var button = document.querySelector("button");

button.addEventListener("click", function () {
  for (i = 0; i < boxes.length; i++) {
    // Pick a random color from the array 'colors'.
    boxes[i].style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
    boxes[i].style.width = '100px';
    boxes[i].style.height = '100px';
    boxes[i].style.display = 'inline-block';
  }
});

button.style.cursor = "pointer";
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<button>Enter</button>

Randomizing the colors on page refresh/load.

// You could easily add more colors to this array.
var colors = ['red', 'blue', 'green', 'teal', 'rosybrown', 'tan', 'plum', 'saddlebrown'];
var boxes = document.querySelectorAll(".box");

for (i = 0; i < boxes.length; i++) {
  // Pick a random color from the array 'colors'.
  boxes[i].style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
  boxes[i].style.width = '100px';
  boxes[i].style.height = '100px';
  boxes[i].style.display = 'inline-block';
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>


Source: stackoverflow