Reputation: 13
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
Reputation: 10262
As per @Roys answer, you need to remove the "\"" and "\""
and you could use below logic as well
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
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
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