Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Set random color (from list) to children

Hi,

I have an idea during developing a new project.

We have a list of element like

<div class="box">
  <div class="select">
  </div>
  <div class="select">
  </div>
  <div class="select">
  </div>
  <div class="select">
  </div>
  <div class="select">
  </div>
  <div class="select">
  </div>
</div>

I have a list of colors like that on javascript, and append random color to all class 'select' above, with a conditional: all child div should have an unique color.

Here is my javascript:

$(document).ready(function () {
    var back = ["#ff0000","blue","gray"];
    var rand = back[Math.floor(Math.random() * back.length)];
    console.log(rand);
    $('.box .select').each(function(i) {
        $(this).css('background',rand);
    });
})

Demo: http://jsfiddle.net/b42vL2p0/

I can append color to all child div with class 'select', but I don't know how to validate and appy UNIQUE color to each one.

**The second thing: Another idea.

How to append random color (don't need to be unique color) to div children, but also ensure all neighbours can not be the same color?

Thank you for your support It helps me alot about javascript through it.

1 Answer

Steven Parker
Steven Parker
230,024 Points

To get different colors, make the selection inside the loop:

$(document).ready(function() {
  var back = ["#ff0000", "blue", "gray"];
  $('.box .select').each(function(i) {
    var rand = back[Math.floor(Math.random() * back.length)];
    //console.log(rand);
    $(this).css('background', rand);
  });
});

Then, to insure adjacent colors are not the same:

  • save last used color and retry random until the result does not match
  • assign in rotating sequence instead of randomly