Random Color From Array
Asked Answered
R

4

10

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.

Recept answered 19/2, 2013 at 2:48 Comment(1)
What have you tried?Causal
M
33

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)]);
});
Medallist answered 19/2, 2013 at 2:54 Comment(9)
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?Recept
I get a syntax error every time I add a dash into the place where you wrote 'myDiv'Recept
That's because you can't have a variable with special characters like -. What element are you trying to select?Medallist
.post-content, I would change it but it's being used in so many files I don't want to end up breaking somethingRecept
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-contentRecept
Yes, by putting the second example in the for loop.Medallist
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.jsRecept
Actually forgot to put it in the $(document).ready(function(){}); tag haha, this seems to work fine, thanks for the help!Recept
Ok. I've edited my answer another time for a simpler solution if you're using jQuery.Medallist
B
4

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());

Berezniki answered 19/2, 2013 at 2:54 Comment(2)
Thanks for that! How could I make this chosen color the background for a given div (i.e. '.post-content')Recept
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).Triumvir
P
2

let hue = 0;
    let colors = []
    for (let j = 0; j < 10; j++) {
        let color = "hsl(" + hue + ",100%,50%)"      
        colors.push(color)      
        hue += 500
    }
    console.log(colors)
Philo answered 4/1, 2022 at 14:0 Comment(0)
H
0

Not sure how well this goes performance wise, but if you're already using lodash it can be as simple as:

// initialising array of colours
let colours = ['tomato', 'salmon', 'plum', 'olive', 'lime', 'chocolate']

// getting a random colour
colours = _.shuffle(colours); // you can shuffle it once, or every time
let hereIsTheColour = colours.pop() // gets the last colour from the shuffled array (also removes it from the array)
Hebetude answered 5/4, 2018 at 10:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.