Applying a random background colour to multiple DIVs

background-color, css, html, jquery

Solution

I dont know your html, but assuming your div are defined as following.

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

The main problem in your code is how you select the elements.

1. Solution

$(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 Demonstration

2. Solution

You can use the following function to get a random color

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;
}

and apply the color using

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

jsFiddle Demonstration

Problem

I have a series of DIVs on the page (each with the same class). On load, I'd like to randomise the colour of each DIV. I'd like a colour to be chosen for a given DIV, then a colour chosen for the next one and so on. I found this post: Apply random color to class elements individually? I don't understand jquery, however I have begun 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 much appreciated! -- Code example here: http://jsfiddle.net/ollyf/LmwYP/ And I should also add the random background colour is from a preset/predetermined list of colours.

Original source

Related problems