3

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);
 });
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
WebStudent
  • 31
  • 1
  • 2

5 Answers5

4

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>
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
2

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>
Obsidian Age
  • 41,205
  • 10
  • 48
  • 71
  • It works but each div is the same color, I want each div to be a random color (e.g 1st div red, 2nd div blue, 3rd div red) for vairety. – WebStudent Aug 28 '18 at 01:02
  • @WebStudent - My apologies; I misinterpreted the question at first. I've updated my answer to showcase each one being different. You may need to hit `Run code snippet` a few times to showcase the randomness :) – Obsidian Age Aug 28 '18 at 02:07
2

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.

Ram
  • 143,282
  • 16
  • 168
  • 197
  • @WebStudent You are very welcome! Here is a jsfiddle for the above code: http://jsfiddle.net/9kxL7dau/3/ – Ram Aug 28 '18 at 01:05
  • mmm... Real cool that use of the [second argument of `.css()`](http://api.jquery.com/css/#css2) +1 *(A snippet would be visually interesting)* – Louys Patrice Bessette Aug 28 '18 at 01:25
2

An approach that uses pure Vanilla JavaScript:

Your divs:

<div class="colour-div"></div>
<div class="colour-div"></div>
<div class="colour-div"></div>
<div class="colour-div"></div>
<div class="colour-div"></div>

And the JS:

var colours = ['red','blue','green','yellow','cyan','orange'];
var divs = document.getElementsByClassName("colour-div");

function generateRandomColors() {
    var i;
    for (i = 0; i < divs.length; i++) {
        var newColor = Math.floor(Math.random()*colours.length)
        divs[i].style.backgroundColor = colours[newColor];
    }
}

The script will continue to function correctly if you:
- Add any number of divs to the colour-div class
- Include any amount of colours to the colours[]

0

I would combine @ObsidianAge and @LouysPatriceBessette answers into one and calculate the color like this so is not restricted to your list...

  var r = Math.random() * 255;
  var g = Math.random() * 255;
  var b = Math.random() * 255;
  var new_color = 'rgb(' + r + ',' g + ',' + b ')';

Should end up with something like this:

$(document).ready(function() {
   $('.color-div').each(function(){
      var r = Math.random() * 255;
      var g = Math.random() * 255;
      var b = Math.random() * 255;
      var new_color = 'rgb(' + r + ',' g + ',' + b ')';
      $(this).css('background-color',new_color);
   });
});

https://jsfiddle.net/xpvt214o/689705/

Edit, just see you said, "From the choices"... sorry, anyway, leave this code here for it may be of use to someone.

Erubiel
  • 2,934
  • 14
  • 32