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);
});
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With