Why is my background generator only changing a strip rather than the whole background?

Viewed 16

I am trying to create a random background changer in JavaScript but running into issues. First of all, it's only changing a strip of the background rather than the whole page. Another question I have is how do I make the button clickable multiple times to keep randomising the background? The code only lets me click once then needing to refresh to change it again.

let btn = document.getElementById('btn');

let randomR = parseInt(Math.floor(Math.random() * 255))
let randomG = parseInt(Math.floor(Math.random() * 255))
let randomB = parseInt(Math.floor(Math.random() * 255))

function backColor() {
  document.body.style.backgroundColor = 'rgb(' + randomR + ',' + randomG + ',' + randomB + ')';
}

btn.addEventListener('click', backColor)
* {
  text-align: center;
  margin: 3% auto;
  color: #fff;
  background-color: #F07DEA;
}

button {
  height: 40px;
  width: 100px;
  border: solid 2px #000;
  border-radius: 5px;
  background-color: #EEEEEE;
  color: #000;
}

button:hover {
  background-color: #000;
  color: #fff;
  border: solid 2px #fff;
}
<body>
  <button class="btn-class" id="btn" onclick="backColor()">
    Click Me!
  </button>
</body>

1 Answers

You want to re-calculate the random R, G, and B values on each click. That means those variables should be defined within the backColor function, so they will be recalculated on each invocation of the function instead of only being calculated once per page load.

Related