Your code works exactly as expected, assuming you have:
- Correctly included jQuery
- Got at least one element with a
class
of color-div
If your code is not working, your problem is most likely that you have not included jQuery. Make sure it is referenced with something like:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here's a working example:
$(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);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color-div">Text</div>
UPDATE
The problem with the above is that the 'random' colour will be the same for each $('.color-div')
element, which may not be desired if there's more than one matching element.
If you want each element to have a different random colour, you'll want to make use of .each()
to iterate over the elements, and target the elements inside of the loop with $(this)
. Also note that you'll want to define new_color
inside the loop.
This can be seen in the following:
$(document).ready(function() {
var colors = ['red', 'blue', 'green', 'yellow', 'cyan', 'orange'];
$.each($('.color-div'), function() {
var new_color = colors[Math.floor(Math.random() * colors.length)];
$(this).css('background-color', new_color);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color-div">Text</div>
<div class="color-div">Text</div>
<div class="color-div">Text</div>
<div class="color-div">Text</div>