Applying a random background color to multiple divs

I have a DIV series on the page (each with the same class). When loading, I would like to randomize the color of each DIV.

I would like to choose a color for this DIV, then choose a color for the next, etc.

I found this post: Apply random color to class elements individually?

I don’t understand jquery, however I started by changing the code to reflect the name of the class I am using:

$(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) + ')';
    $(.jump-response).css("background-color", hue);
});
});

Further help would be greatly appreciated!

-

Sample code here: http://jsfiddle.net/ollyf/LmwYP/

And I also have to add a random background color from a predefined / predefined list of colors.

+5
source share
4 answers

html, , div .

<div class="jump-response">one</div>
<div class="jump-response">two</div>

, .

1.

$(function() {
    $(".jump-response").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);
    });
});

jsFiddle

2.

function get_random_color() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
}

,

$(".jump-response").each(function() {
    $(this).css("background-color", get_random_color());
});

jsFiddle

+21

, .jump-response

$(".jump-response").css("background-color", hue);

, "main", , , .

0

$(document).ready(function() {
  $('.jump-response').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);
  });
});
0

, :

javascript:jQuery("div").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) + ')';jQuery(this).css("background-color", hue);});

"javascript:" ( ), jQuery.

0

All Articles