Reputation: 399
I'm trying to randomise the background colour of ten containers. Using the current jQuery, the colour is randomised on load however the same colour is used for all of the containers. How would I alter the code to call separately for each instance of .box
$(document).ready(function(){
var colors = ["#BF2642","#191B29","#366377"];
var rand = Math.floor(Math.random()*colors.length);
$('.box').css("background-color", colors[rand]);
});
Upvotes: 0
Views: 20
Reputation: 382092
Just loop over the .box
elements and compute rand
for each one:
$(document).ready(function(){
var colors = ["#BF2642","#191B29","#366377"];
$('.box').each(function(){
var rand = Math.floor(Math.random()*colors.length);
$(this).css("background-color", colors[rand]);
});
});
Upvotes: 3