Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I give each individual div a random background color?

I'm building a website and I want each div on the page to be a random color from the choices below. But once I run the code each of the divs are the same color. Where am I going wrong?

 $(document).ready(function(){ 
   var colors = ['red','blue','green','yellow','cyan','orange'];
   var new_color = colors[Math.floor(Math.random()*colors.length)];
   $('.color-div').css('background-color',new_color);
 });
like image 575
WebStudent Avatar asked Oct 27 '25 17:10

WebStudent


2 Answers

Here is a solution where you loop through all .color-div and set a "random" color for each.

it uses the .each() method.

Your code was right... but ran only once and applied the color to all elements.

$(document).ready(function(){

  var colors = ['red','blue','green','yellow','cyan','orange'];
  
  $('.color-div').each(function(){
    var new_color = colors[Math.floor(Math.random()*colors.length)];
    $(this).css('background-color',new_color);
  });
 
});  // End ready
div{
  height:2em;
  width: 2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color-div"></div>
<div class="color-div"></div>
<div class="color-div"></div>
<div class="color-div"></div>
<div class="color-div"></div>
like image 120
Louys Patrice Bessette Avatar answered Oct 29 '25 07:10

Louys Patrice Bessette


Your code uses a random color for all elements. You need to get a random color for each element. This means iteration.

The following code gets a random color for each element:

var colors = ['red','blue','green','yellow','cyan','orange'];
$('.color-div').css('background-color', function() {
    var i = Math.floor(Math.random()*colors.length);
    var color = colors[i];
    colors.splice(i, 1);
    return color;
}); 

The above code makes sure that a color is only used once. If having 2 or more elements with the same color is acceptable, you can remove the colors.splice line. Also note that the code with the splice statement assumes there are not more than 6 .color-div elements.

like image 23
undefined Avatar answered Oct 29 '25 06:10

undefined



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!