monkee
monkee

Reputation: 399

Random list element, multiple calls

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

Answers (1)

Denys Séguret
Denys Séguret

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

Related Questions