Random Color From Array
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)];
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());
Tomelower
Updated on July 09, 2022Comments
-
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 about 11 yearslooks 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 about 11 yearsThanks for that! How could I make this chosen color the background for a given div (i.e. '.post-content')
-
Tomelower about 11 yearsI get a syntax error every time I add a dash into the place where you wrote 'myDiv'
-
Austin Brunkhorst about 11 yearsThat's because you can't have a variable with special characters like
-
. What element are you trying to select? -
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 about 11 yearsIs 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 about 11 yearsYes, by putting the second example in the for loop.
-
Tomelower about 11 yearsStill 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 about 11 yearsActually forgot to put it in the $(document).ready(function(){}); tag haha, this seems to work fine, thanks for the help!
-
Austin Brunkhorst about 11 yearsOk. I've edited my answer another time for a simpler solution if you're using jQuery.
-
Radvylf Programs over 5 yearsYou 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
tooverflowY
,font-size
tofontSize
).