I've been working on a project where I want to input a number into a form and generate that many boxes with random colored backgrounds when I press go.
Here is the current JavaScript code:
<script type="text/javascript">
var number = 3;
function numBoxes(){
var form = document.getElementById("form1");
var container = document.getElementById("container");
while (container.children.length > 0) {
container.removeChild(container.firstElementChild);
}
number = form.elements["number"].value;
setup();
}
function setup(){
var container = document.getElementById("container");
for (var i = 0; i < number; i++) {
var box = document.createElement("div");
box.id = "newdiv"
container.appendChild(box);
var d = document.getElementById("newdiv");
var colors = random_bg_color();
d.style.backgroundColor = colors;
}
}
function random_bg_color(){
var x = Math.floor(Math.random() * 256);
var y = Math.floor(Math.random() * 256);
var z = Math.floor(Math.random() * 256);
var bgColor = "rgb(" + x + "," + y + "," + z + ")";
return bgColor;
}
</script>
The only thing challenging for me has been assigning a random rgb color to each newly created division or box.
Please note, this task should be accomplished without using jQuery.