Random color from array

I want to create 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.

Does anyone know a good way to do this? Nothing works for me, but I'm not a very experienced person.

+3


source to share


3 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 compress it to known colors, you can create an array of colors and randomly select it like this.

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

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

      

JSFiddle

Update . Using the first method for everyone .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 one .post-content

individually, you can.

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(',') +')';
}

      

The last update is 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)]);
});

      

+12


source


This example returns a random element from any array, if you pass the non-falsey argument it removes the element 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];
}

      

//example:



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

      

alerts (colors.getRandom ());

+3


source


Not sure how well this matches performance, but if you are already using lodash it might just be:

// 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)

      

0


source







All Articles