Random color on different div's
You could use class
es instead of id
s 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>
How about this?
http://jsfiddle.net/stackmanoz/vymmb10s/
CSS-
div[class^="box"]{
width:100px;
height:100px;
border:1px solid;
display:inline-block;
}
jQuery-
var colors = ['red', 'blue', 'green', 'gray', 'black', 'yellow'];
$(function(){
$("#btn").click(function() {
$('div[class^="box"]').each(function(){
var randomColor = Math.floor(Math.random() * colors.length)
$(this).css('background-color', colors[randomColor])
});
});
});