Reputation: 951
Here is my code:
var randomColor = ["red", "blue", "green", "#9CBA7F", "yellow", "#BF5FFF"];
function setRandomColor() {
return randomColor[Math.floor(Math.random() * randomColor.length)];
}
$('.mastermind_master_cpu').each(function() {
$(this).find('td').each(function() {
$(this).css("background-color", setRandomColor);
})
})
As you can see, the mastermind_master_cpu table will randomly fill with different background color. The problem is I have ten different tables and am repeating this every time. Does anyone know how I can go about making this just one function / variable and calling it when needed?
Thanks!
Upvotes: 1
Views: 78
Reputation: 149020
Create a class, say random_color
, to apply to each table in addition to your current class, like this:
<table class="mastermind_master_cpu random_color">...</table>
Then you can just use this once:
$('.random_color').each(function() {
$(this).find('td').each(function() {
$(this).css("background-color", setRandomColor);
})
})
But as cookie monster points out, this can be done much more succinctly:
$('.random_color td').css("background-color", setRandomColor);
Upvotes: 3