Reputation: 59
I have a "var rgb" that generates a RGB color for each click in a div. Now i want to randomly apply it as background color to one of the div's inside "#game". How can i do it?
index.html
<header>
<p class="great">xxx</p>
<p id="rgb">RGB(143, 80, 16)</p>
<p class="great">xxxx</p>
</header>
<nav>
<div id="game">
<div id="newColors">NEW COLORS</div>
<div id="result">RESULT</div>
<div id="easy"><span>EASY</span> <span>HARD</span></div>
</div>
</nav>
<div id="game">
<div class="firstSquare"></div>
<div class="secondSquare"></div>
<div class="thirdquare"></div>
<div class="firstSquare"></div>
<div class="secondSquare"></div>
<div class="thirdquare"></div>
</div>
script.js
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
var rgb = "RGB(" + r + "," + g + "," + b + ")";
var colorRGB = document.getElementById("rgb");
var headerRGB = document.getElementById("newColors");
var squareOne = document.getElementById("one");
headerRGB.addEventListener("click", function() {
colorRGB.textContent = rgb;
squareOne.style.backgroundColor = "rgb";
});
Upvotes: 0
Views: 56
Reputation: 16777
rgb
is a variable, not a string. You accidentally put it in quotes. Try:
squareOne.style.backgroundColor = rgb
Also, if you want to generate a new random color on each click, put your randomization logic inside the event listener:
var colorRGB = document.getElementById("rgb")
var headerRGB = document.getElementById("newColors")
var game = document.getElementById("game")
headerRGB.addEventListener("click", function() {
var r = Math.floor(Math.random() * 255)
var g = Math.floor(Math.random() * 255)
var b = Math.floor(Math.random() * 255)
var rgb = "RGB(" + r + "," + g + "," + b + ")"
colorRGB.textContent = rgb
var div = game.children[Math.floor(Math.random() * game.children.length)]
div.style.backgroundColor = rgb
})
Upvotes: 1