Random Color From Array

65,501

Solution 1

How about this?

var rgb = [];

for(var i = 0; i < 3; i++)
    rgb.push(Math.floor(Math.random() * 255));

myDiv.style.backgroundColor = 'rgb('+ rgb.join(',') +')';

If you want to constrict it to known colors, you can create an array of the colors and randomly select it like so.

var colors = ['red', 'green', 'blue', 'orange', 'yellow'];

myDiv.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];

JSFiddle

Update - Using the first method to apply to all .post-content.

var divs = document.querySelectorAll('.post-content');

for(var i = 0; i < divs.length; i++)
    divs[i].style.backgroundColor = 'rgb('+ rgb.join(',') +')';

If you want to apply a random background to each .post-content individually, you would do this.

var divs = document.querySelectorAll('.post-content');

for(var i = 0; i < divs.length; i++) {
    var rgb = [];

    for(var i = 0; i < 3; i++)
        rgb.push(Math.floor(Math.random() * 255));

    divs[i].style.backgroundColor = 'rgb('+ rgb.join(',') +')';
}

Last Update - using jQuery, as you mentioned.

var colors = ['red', 'green', 'blue', 'orange', 'yellow'];

$('.post-content').each(function() {
    $(this).css('background-color', colors[Math.floor(Math.random() * colors.length)]);
});

Solution 2

This example returns a random item from any array, if you pass a non-falsey argument, it removes the item from the array.

Array.prototype.getRandom= function(cut){
    var i= Math.floor(Math.random()*this.length);
    if(cut && i in this){
        return this.splice(i, 1)[0];
    }
    return this[i];
}

//sample:

var colors= ['aqua', 'black', 'blue', 'fuchsia', 'gray', 'green', 
'lime', 'maroon', 'navy', 'olive', 'orange', 'purple', 'red', 
'silver', 'teal', 'white', 'yellow'];

alert(colors.getRandom());

Share:
65,501
Tomelower
Author by

Tomelower

Updated on July 09, 2022

Comments

  • Tomelower
    Tomelower almost 2 years

    I'm looking to build something with JavaScript that will pick a random value (background-color) from an array of given hex colors and apply it to a given div element.

    Anyone know a good way to do this? Nothing seems to be working for me but I'm not really a JS savvy person.

  • Tomelower
    Tomelower about 11 years
    looks great! I've been able to get the random color but couldn't properly apply it to the style, any way to use a class with a '-' in it without getting an error?
  • Tomelower
    Tomelower about 11 years
    Thanks for that! How could I make this chosen color the background for a given div (i.e. '.post-content')
  • Tomelower
    Tomelower about 11 years
    I get a syntax error every time I add a dash into the place where you wrote 'myDiv'
  • Austin Brunkhorst
    Austin Brunkhorst about 11 years
    That's because you can't have a variable with special characters like -. What element are you trying to select?
  • Tomelower
    Tomelower about 11 years
    .post-content, I would change it but it's being used in so many files I don't want to end up breaking something
  • Tomelower
    Tomelower about 11 years
    Is there a way to use the other technique so I can define what colors it selects from and have it applied to each .post-content
  • Austin Brunkhorst
    Austin Brunkhorst about 11 years
    Yes, by putting the second example in the for loop.
  • Tomelower
    Tomelower about 11 years
    Still doesn't seem to work, even the one you provided in your most recent edit doesn't effect the site. I've tried it in the <head> tag, in the <body> or under </body> Actually in the last case it crashes Firefox haha Is the a .js library I should be importing? Currently using jquery-1.7.1.min.js
  • Tomelower
    Tomelower about 11 years
    Actually forgot to put it in the $(document).ready(function(){}); tag haha, this seems to work fine, thanks for the help!
  • Austin Brunkhorst
    Austin Brunkhorst about 11 years
    Ok. I've edited my answer another time for a simpler solution if you're using jQuery.
  • Radvylf Programs
    Radvylf Programs over 5 years
    You would use document.getElementById("myDiv").style.backgroundColor = colors.getRandom();. In order to use a CSS property with a dash, just capitalize the next letter instead (overflow-y to overflowY, font-size to fontSize).