Mozar Mozar - 4 months ago 9
Javascript Question

Randomly colored circle

I am working on a little project which assigns a random color to this circle from all the possible colors.

I am trying to achieve this by assigning a random number to each RGB value. However, It doesn't seem to work this way. I also tried to setAttribute() way to assign it that way but also no luck. Please have a look:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Beginning JavaScript</title>
<style>




#circle{
margin:auto;
border:1px solid black;
border-radius: 50%;
background-color:rgb(0,0,0);
height:200px;
width:200px;
}


</style>
</head>
<body>
<div id="circle"></div>
<script>

var circle = document.getElementById('circle');
var value1 = Math.floor(Math.random() * 256);
var value2 = Math.floor(Math.random() * 256);
var value3 = Math.floor(Math.random() * 256);
circle.style.backgroundColor = "rgb(value1,value2,value3)"

Answer

You need to concatenate the generated values into the style statement:

circle.style.backgroundColor = "rgb(" + value1 + "," + value2 + "," + value3 + ")";