Wrote the code

function randColor() { var red = Math.round(Math.random()*255); var blue = Math.round(Math.random()*255); var green = Math.round(Math.random()*255); document.getElementById('boby').style.backgroundColor = "rgb+"("+txt+")""; var txt = (+red+", "+blue+", "+green); alert("rgb"+"("+txt+")"); } 

to change the background body by clicking. Through alert it is clear that rgb transmits the correct one and if, instead of what gives out "rgb +" ("+ txt +") "" to write what gives out the alert, then everything will work, but the code itself does not work. Who can tell why?

    1 answer 1

    Still, it is better to first assign a value to a variable, and then use it.

     function randColor() { var red = Math.round(Math.random() * 255); var blue = Math.round(Math.random() * 255); var green = Math.round(Math.random() * 255); var txt = (+red + ", " + blue + ", " + green); //alert("rgb"+"("+txt+")"); document.getElementById('boby').style.backgroundColor = "rgb(" + txt + ")"; } setInterval(randColor, 500); 
     #boby { width:200px; height:100px; border:1px solid black; } 
     <div id="boby"></div> <button onclick="randColor()">Click</button> 

    • just noticed, but exactly thanks)) - Tigran Vardanyan