slurp
slurp

Reputation: 13

Assign a random rgb background color to HTML body via javascript

Title says most of it. I want to add an event to a button that changes the body's background on click. See my code:

document.querySelector("button").addEventListener("click", function(){
    var randomColors = [];
    var rgbString = "rgb(";
    for(var i = 0; i <= 2; i++){
        randomColors[i] = Math.floor(Math.random() * (255 + 1));
        if(i < 2){
            rgbString += randomColors[i].toString() + ",";
        }else{
            rgbString += randomColors[i].toString() + ")";
        }
    }
    document.body.style.background = "\"" + rgbString + "\"";
});

i've been struggling way too long on this one. Since console.log("\"" + rgbString + "\"") returns a proper string, eg. "rgb(0,55,103)" i fail to figure out the mistake.

Thanks a lot!

Upvotes: 1

Views: 334

Answers (3)

Narendra Jadhav
Narendra Jadhav

Reputation: 10262

As per @Roys answer, you need to remove the "\"" and "\"" and you could use below logic as well

ES6

You can create a function with random value of rgb color and use new Array(3).fill('').map() to achieve result


const random=() => Math.floor(Math.random() * (255 + 1));

document.querySelector("button").addEventListener("click", ()=>{
     document.body.style.background = `rgb(${new Array(3).fill('').map(v=>random()).join(',')})`
});
<button>Change color</button>

Upvotes: 0

Nikas music and gaming
Nikas music and gaming

Reputation: 1282

This is the shortest answer I found

document.querySelector("button").addEventListener("click", function(){
    var randomColors = [];
    var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
    randomColors.push(hue);
    console.log(hue);
    document.body.style.background = hue;
});
<button>change color</button>

Upvotes: 0

Roy Bogado
Roy Bogado

Reputation: 4462

remove the "\"" and "\"" from document.body.style.background = "\"" + rgbString + "\""

document.querySelector("button").addEventListener("click", function(){
    var randomColors = [];
    var rgbString = "rgb(";
    for(var i = 0; i <= 2; i++){
        randomColors[i] = Math.floor(Math.random() * (255 + 1));
        if(i < 2){
            rgbString += randomColors[i].toString() + ",";
        }else{
            rgbString += randomColors[i].toString() + ")";
        }
    }
    console.log(rgbString)
    document.body.style.background = rgbString
});
<button>
button
</button>

Upvotes: 1

Related Questions