Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random Color From Array

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.

like image 775
Tomelower Avatar asked Feb 19 '13 02:02

Tomelower


1 Answers

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)]);
});
like image 174
Austin Brunkhorst Avatar answered Sep 21 '22 15:09

Austin Brunkhorst