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.
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)]);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With