How to randomly color Divs with a Javascript Color Array?

Asked

Viewed 4,097 times

16

I created a function that changes colors (pulled from one array) on certain page elements (which are also on array), but it was very strange, as it changes the colors of the elements one after the other. I wanted to do something different, like: Draw the element and the color that will be modified. How I adapt my function to do this?
Example -> http://jsbin.com/citoq/1/watch?output

window.onload = function(){
    var box = document.getElementsByClassName('box');
    var background = ["#f36", "#C3C", "#fc0", "#FC6", "#9C0"];
    cor=0;
    div=0;
    setInterval(function(){
            box.item(div).style.backgroundColor = background[cor];
            cor++; div++;
            if(cor>=background.length){
                cor=0;}
            if(div>=box.length){
                div=0;}
        },2000)
}
  • You want colors to appear from this vector of "random"?

  • Yes, I want both colors, as many elements to be randomly exchanged

  • 2

    You can check out here your answer

  • Thank you @Erloncharles!

3 answers

7


I imagine what you want is this:

window.onload = function(){
    var box = document.getElementsByClassName('box');
    var background = ["#f36", "#C3C", "#fc0", "#FC6", "#9C0"];
    cor=0;
    div=0;
    setInterval(function(){
            cor = Math.floor(Math.random() * (background.length - 1));
            div = Math.floor(Math.random() * (background.length - 1));
            box.item(div).style.backgroundColor = background[cor];
        },2000)
}

If you do not want to repeat the colors, you can do the following: (Remembering that the same can be done for div also)

var coresQueNaoForam = [0,1,2,3,4];
window.onload = function(){
    var box = document.getElementsByClassName('box');
    var background = ["#f36", "#C3C", "#fc0", "#FC6", "#9C0"];
    cor=0;
    div=0;
    setInterval(function(){
            cor = Math.floor(Math.random() * (coresQueNaoForam.length - 1));
            div = Math.floor(Math.random() * (background.length - 1));
            box.item(div).style.backgroundColor = background[coresQueNaoForam.splice(cor,1)];
            if(coresQueNaoForam.length == 0){
              coresQueNaoForam = [0,1,2,3,4];
            }              
        },2000)
}
  • 1

    Exactly @Felipe, thanks very guy!

5

You can use Math.()

var arrCores = ['#f00', '#0f0', '#0ff'];

setInterval(function(){
    document.getElementById('divRandom').style.backgroundColor = arrCores[Math.round(Math.random()*(arrCoresSize-1))]
}, 500);

jsFiddle

Colors that do not repeat

var arrCores = ['#f00', '#0f0', '#0ff'];
var arrCoresUsadas = [];

setInterval(function(){
    // Define cor aleatória
    var index = Math.round(Math.random() * (arrCores.length-1));
    document.getElementById('divRandom').style.backgroundColor = arrCores[index];

    // Marca cor como usada
    arrCoresUsadas.push(arrCores[index]);
    arrCores.splice(index, 1);

    // Todas as cores usadas, começa tudo de novo:
    if (arrCores.length === 0){
        arrCores = arrCoresUsadas;
        arrCoresUsadas = [];
    }
}, 500);

jsFiddle


In such cases, I’m expecting the array to contain elements... By price, there could be an if’s to avoid errors, if the arrays can be empty for some reason.

  • Thank you so much @Andre!

1

Answer:

You can randomize a hexadecimal color using Math.floor() and Math.random() in this way:

var corRandom = '#'+Math.floor(Math.random()*16777215).toString(16);

Explanation:

A hexadecimal color should start with the '#' character so the concatenation, before the generation of the randomic function, calculating to get a hexadecimal result and being converted to String using toString().

You should not, do not need to use an Array to store colors, since they can be generated.

Your code would look like this using this method mentioned above:

var box = document.getElementsByClassName('box');
div=0;
setInterval(function(){
        box.item(div).style.backgroundColor = '#'+Math.floor(Math.random()*16777215).toString(16);
        div++;
        if(div>=box.length){
            div=0;
        }
    },2000);

Example running on Jsfiddle

  • Thanks for the help @Paulo! Very useful

  • I don’t understand why not store the colors pq they can be generated.. And if I want to randomize between 5 predetermined colors for example?

  • Well, now that you said it, I read the title of the question again and it really wants predetermined colors so it wouldn’t be quite that, but it’s an alternative.. at least it was useful.

  • 1

    Yes, in fact I wanted predetermined colors @Pauloroberto so there is no danger that the colors do not match the rest of the layout, but this example of yours was very useful, I had no idea that this could be done.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.