Fofaster
Fofaster

Reputation: 127

I'm not sure how to reset the backgroundColor value

Right now I'm trying to develop a very simple button that changes the background color of the whole webpage. Here is the code I have

var mybutton = document.querySelector('button');
var myBack = document.querySelector("body");
var isRand = false;

var ranNumber1 = Math.floor(Math.random() * 256);
var ranNumber2 = Math.floor(Math.random() * 256);
var ranNumber3 = Math.floor(Math.random() * 256);
var RanRGB = "rgb(" + ranNumber1 + "," + ranNumber2 + "," + ranNumber3 + ")";


mybutton.addEventListener("click", function() {

  if (isRand) {
    myBack.style.backgroundColor = "white";
    isRand = false;
  } else {
    myBack.style.backgroundColor = RanRGB
    isRand = true;
  }
});
<!DOCTYPE html>
<html>
    <head>
        <title>toggle</title>
    </head>
    <body>
        <div>
            <button>click here!</button>
        </div>
        <script type="text/javascript" src="togglescript.js"></script>
    </body>
</html>

When this webpage loads and I click the button, the background color changes to a random color from white. Then if i click again it turn white again. This is what I want. However, then I want to be able to click the button again and change the color to a new random color. Currently it just changes it background back to the color it generated originally. How do I reset the background color?

Upvotes: 0

Views: 33

Answers (1)

Chris Riebschlager
Chris Riebschlager

Reputation: 1333

Move the color generation into your function.

var mybutton = document.querySelector('button');
var myBack = document.querySelector("body");
var isRand = false;

mybutton.addEventListener("click", function() {

    var ranNumber1 = Math.floor(Math.random() * 256);
    var ranNumber2 = Math.floor(Math.random() * 256);
    var ranNumber3 = Math.floor(Math.random() * 256);
    var RanRGB = "rgb(" + ranNumber1 + "," + ranNumber2 + "," + ranNumber3 + ")";

  if (isRand) {
    myBack.style.backgroundColor = "white";
    isRand = false;
  } else {
    myBack.style.backgroundColor = RanRGB
    isRand = true;
  }
});

Upvotes: 2

Related Questions