I have 3 div’s
JavaScript
x
5
1
<div id="box1"></div>
2
<div id="box2"></div>
3
<div id="box3"></div>
4
<button>Enter</button>
5
I want to give it a random color using javascript controlled css. Like this:
JavaScript
1
33
33
1
var randomColor = Math.ceil(Math.random() * 3);
2
var color = "";
3
//Accessing the divs
4
var box1 = document.querySelector("#box1");
5
var box2 = document.querySelector("#box2");
6
var box3 = document.querySelector("#box3");
7
8
//Event
9
var button = document.querySelector("button");
10
button.addEventListener("click", randomize, false);
11
button.style.cursor = "pointer";
12
13
function render(){
14
box1.style.background = color;
15
box2.style.background = color;
16
box3.style.background = color;
17
}
18
19
function randomize(randomColor){
20
switch(randomColor){
21
case 1:
22
color = "red";
23
break;
24
case 2:
25
color = "blue";
26
break;
27
case 3:
28
color = "green";
29
break;
30
}
31
render();
32
}
33
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..
Advertisement
Answer
You could use class
es instead of id
s and simplify your code to following.
JavaScript
1
16
16
1
// You could easily add more colors to this array.
2
var colors = ['red', 'blue', 'green', 'teal', 'rosybrown', 'tan', 'plum', 'saddlebrown'];
3
var boxes = document.querySelectorAll(".box");
4
var button = document.querySelector("button");
5
6
button.addEventListener("click", function () {
7
for (i = 0; i < boxes.length; i++) {
8
// Pick a random color from the array 'colors'.
9
boxes[i].style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
10
boxes[i].style.width = '100px';
11
boxes[i].style.height = '100px';
12
boxes[i].style.display = 'inline-block';
13
}
14
});
15
16
button.style.cursor = "pointer";
JavaScript
1
4
1
<div class="box"></div>
2
<div class="box"></div>
3
<div class="box"></div>
4
<button>Enter</button>
Randomizing the colors on page refresh/load.
JavaScript
1
11
11
1
// You could easily add more colors to this array.
2
var colors = ['red', 'blue', 'green', 'teal', 'rosybrown', 'tan', 'plum', 'saddlebrown'];
3
var boxes = document.querySelectorAll(".box");
4
5
for (i = 0; i < boxes.length; i++) {
6
// Pick a random color from the array 'colors'.
7
boxes[i].style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
8
boxes[i].style.width = '100px';
9
boxes[i].style.height = '100px';
10
boxes[i].style.display = 'inline-block';
11
}
JavaScript
1
3
1
<div class="box"></div>
2
<div class="box"></div>
3
<div class="box"></div>