Reputation: 1
I want to append divs to a parent div, each smaller div being a random background color chosen from an array. How would I do so?
What I already have:
$(document).ready(function(){
var cell_size = 10;
var container = $("#container");
var colors = ["limepulp", "goldgreen", "chromeoxidegreen", "kermit", "pear"];
/* Get the cell dimentions and populate the grid */
var cell_height_num = container.height() / cell_size; /* This is equal to 50 */
var cell_width_num = container.width() / cell_size; /* This is also equal to 50 */
for (var i = 0; i < cell_width_num * cell_height_num; i++){
/* What goes here? How can I generate a div with a random background comming from colors[]? */
/* In total, 2500 divs should be generated inside $("#container"); */
}
});
Upvotes: 0
Views: 364
Reputation: 169401
This is better suited to a <table>
code:
/* Get the cell dimentions and populate the grid */
var cell_height_num = 50; /* This is equal to 50 */
var cell_width_num = 50; /* This is also equal to 50 */
for (var i = 0; i < cell_height_num; i++) {
var tr = $("<tr></tr>").appendTo(container);
for (var j = 0; j < cell_width_num; j++) {
tr.append($("<td></td>", {
css: {
width: "1px",
height: "1px",
backgroundColor: colors[Math.floor(Math.random() * colors.length)]
}
}));
}
}
Upvotes: 0
Reputation: 1038820
var colors = [ 'red', 'blue', 'green', '#ffe' ];
...
for (var i = 0; i < cell_width_num * cell_height_num; i++) {
var color = colors[Math.floor(Math.random() * colors.length)];
$('#container').append(
$('<div/>', {
style: 'background-color:' + color,
text: 'some text'
})
);
}
Also note that colors contained in the colors array are not valid CSS color names. You could use the #RGB equivalent to define them.
Upvotes: 1