David
David

Reputation: 11

Random hexadecimal color

How to change the style.color to an hexadecimal random value with this code ?

hexaTable = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f'];
    document.getElementById("button").onclick=
        function(){
            if (x==true) {
                document.getElementById("text").innerHTML="Au revoir";
                document.getElementById("text").style.color="#" + 6 * hexaTable [Math.floor(Math.random() * hexaTable.length)];
                x=false;
            }
            else {
                document.getElementById("text").innerHTML="Bonjour";
                x=true;
            }
        };

Upvotes: 1

Views: 115

Answers (3)

Pranav Gupta
Pranav Gupta

Reputation: 944

one line solution to this would be:

'#'+('000000'+parseInt(Math.random()*(256*256*256-1)).toString(16)).slice(-6)

Upvotes: 1

Royi Namir
Royi Namir

Reputation: 148524

Try this :

This will create random hex colors : (using recursion)

   console.log('#' + (function co(a) {
       return(a += [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f'][~~(Math.random() * 16)]) && (a.length == 6) ? a : co(a);
})(''))

enter image description here

So :

document.getElementById("text").style.color='#' + (function co(a) {
           return(a += [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f'][~~(Math.random() * 16)]) && (a.length == 6) ? a : co(a);
    })('');

http://jsbin.com/ULenuFa/3/edit

Upvotes: 3

Borre Mosch
Borre Mosch

Reputation: 4564

You will actually have to repeat hexaTable[Math.floor(Math.random() * hexaTable.length)] six times, e.g.:

document.getElementById("text").style.color="#" +
    hexaTable[Math.floor(Math.random() * hexaTable.length)] +
    hexaTable[Math.floor(Math.random() * hexaTable.length)] +
    hexaTable[Math.floor(Math.random() * hexaTable.length)] +
    hexaTable[Math.floor(Math.random() * hexaTable.length)] +
    hexaTable[Math.floor(Math.random() * hexaTable.length)] +
    hexaTable[Math.floor(Math.random() * hexaTable.length)];

Upvotes: 0

Related Questions