views:

478

answers:

3

My goal is to each div with a class of "main" to have a random background color. I have the script that generates the random color but, using jquery, I only seem to be able to apply it to all divs in the class. How can I select a div, apply the color, select the next div in the class, generate a new random color, apply it and repeat? Here's my code:

$(document).ready(function() {
    var hue = 'rgb(' + (Math.floor((256-199)*Math.random()) + 200) + ','
                     + (Math.floor((256-199)*Math.random()) + 200) + ','
                     + (Math.floor((256-199)*Math.random()) + 200) + ')';
    $('.main').css("background-color", hue);
});
+1  A: 

The code should be something like this...

$(document).ready(function() {
                        $('.main').each{ Function(){
                             $(this).css("background-color", hue); };
                        };
                });

Bah- sorry for the mistakes. Fixed the worst of them for my own sanity's sake.. but the other answer beat me to it.

apocalypse9
I think you should be calling getHue() in your anonymous function
RMorrisey
You are right- I had just fixed that in my code. I was scrambling and doing things wrong. The other answer is actually competent.
apocalypse9
+3  A: 
$(document).ready(function() {
    $('.main').each(function () {
     var hue = 'rgb(' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ')';
     $(this).css("background-color", hue);
    });
});
Beetny
Perfect. Thanks!
Johnny
+1  A: 
$(document).ready(function() {
  $('.main').each(function(){
    var hue = 'rgb(' + (Math.floor((256-199)*Math.random()) + 200) + ',' + 
      (Math.floor((256-199)*Math.random()) + 200) + ',' + 
      (Math.floor((256-199)*Math.random()) + 200) + ')';
    $(this).css("background-color", hue);
  }
});
Marius