Coloured -Squares - Getting Elements by Id and Class Name
Demonstration of setting background colour of div elements by Id and Class Name.
HTML
<!-- Business Web Technology (ISYS3004) -->
<!-- School of Information Systems -->
<!-- Curtin University -->
<h2>Click a Square </h2>
<div id="board">
<div id="box11" class="square" onclick="randomBackground('box11')"></div>
<div id="box12" class="square" onclick="randomBackground('box12')"></div>
<div id="box13" class="square" onclick="randomBackground('box13')"></div>
<div id="box21" class="square" onclick="randomBackground('box21')"></div>
<div id="box22" class="square" onclick="randomBackground('box22')"></div>
<div id="box23" class="square" onclick="randomBackground('box23')"></div>
<div id="box31" class="square" onclick="randomBackground('box31')"></div>
<div id="box32" class="square" onclick="randomBackground('box32')"></div>
<div id="box33" class="square" onclick="randomBackground('box33')"></div>
</div>
<button onclick="randomBoard()">Random</button>
<button onclick="clearBoard()">Clear</button>
<h3> Instructions </h3>
<UL>
<li>Click a square to change the colour for that element id.</li>
<li>Click the random button to set a random colour for each element id. </li>
<li>Click the clear button to sets all squares to single colour for the entire class.</li>
</UL>
CSS
#board {
width: 300px;
height: 300px;
}
.square {
width: 100px;
height: 100px;
float: left;
}
JavaScript
var color = ["red", "green", "blue", "magenta", "lightblue", "yellow", "goldenrod", "palegoldenrod", "salmon", "pink", "indigo", "lightgreen", "lightblue", "plum", "cornflowerblue"];
var clearColor = "black";
// Return a random colour from the list
function randomColor() {
return color[Math.floor((Math.random() * color.length))];
}
// Randomly generate a new colour for each id
function randomBoard() {
for (var col=1 ; col <= 3 ; col++) {
for (var row=1 ; row <= 3 ; row++) {
var square = "box" + row + col;
document.getElementById(square).style.backgroundColor = randomColor();
}
}
}
// Set the colour for the entire class
function clearBoard() {
var square = document.getElementsByClassName("square");
for (var i=0; i<square.length ; i++) {
square[i].style.backgroundColor = clearColor;
}
}
randomBoard();