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..
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..
Share Improve this question asked Jan 6, 2015 at 12:55 Dexter C. Caga-ananDexter C. Caga-anan 831 gold badge1 silver badge3 bronze badges 1 |5 Answers
Reset to default 12You 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])
});
});
});
var r = Math.floor(Math.random()*255);
var g = Math.floor(Math.random()*255);
var b = Math.floor(Math.random()*255);
for (var i = 0; i <= 5; i++) {
var div = document.getElementsByClassName("div")[i].style.backgroundColor = "rgb("+r+","+g+","+b+")";
}
div {
width: 200px;
height:200px;
display: inline;
float: left;
margin: 15px;
background-color: red;
}
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
*
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
position: relative;
border: 1px solid black;
float: left;
margin: 5px;
}
</style>
</head>
<body>
<div id="first"></div>
<div id="second"></div>
<div id="third"></div>
<div id="fourth"></div>
</body>
<script>
let colors = ['red', 'green', 'blue', 'yellow'];
(function () {
document.getElementById("first").style.backgroundColor = assignColor();
document.getElementById("second").style.backgroundColor = assignColor();
document.getElementById("third").style.backgroundColor = assignColor();
document.getElementById("fourth").style.backgroundColor = assignColor();
})();
function assignColor() {
let colorIndex = Math.floor(Math.random() * colors.length);
let color = colors[colorIndex];
colors.splice(colorIndex, 1);
return color;
}
</script>
</html>
I was appalled by the list of named string colors and didn't see anyone using hex. For anyone like me that wanted something different, here you go:
function randomInt(max=1, min=0){
// scale random number from 0 to 1 to desired min and max
return parseInt( Math.random() * (max - min) + min );
}
function twoPlaces(sNum=''){
// make sure all strings have a length greater than 1
// eg: "f" => "0f"
return sNum.length > 1 ? sNum : twoPlaces('0'+sNum);
}
function randomColor(){
// make each color's hex string
let r = twoPlaces( randomInt(255,0).toString(16) );
let g = twoPlaces( randomInt(255,0).toString(16) );
let b = twoPlaces( randomInt(255,0).toString(16) );
// return hex color string
return `#${r}${g}${b}`;
}
function updateColors(){
// loop through all elements with class "random"
document.querySelectorAll(".random").forEach( (el)=>{
// set each element/'s color to a random hex
el.setAttribute("style",`background-color:${ randomColor() }`);
} );
}
// add function to randomizer
let randomizer = document.querySelector("#colorRandomizer");
randomizer.addEventListener("click",updateColors);
// initialize colors
randomizer.dispatchEvent( new Event("click") );
div {
width: 100%;
height: 100%;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
}
.random{
height: 100px;
}
<button id="colorRandomizer">Randomize</button>
<div>
<div class="random"></div>
<div class="random"></div>
<div class="random"></div>
<div class="random"></div>
<div class="random"></div>
<div class="random"></div>
</div>
randomColor
definition intorandomize
function. – Teemu Commented Jan 6, 2015 at 12:58