-2

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>
isherwood
  • 58,414
  • 16
  • 114
  • 157

1 Answers1

0

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.

Tom
  • 8,509
  • 7
  • 49
  • 78
  • thanks everyone, i moved the properties in the * element on css into the body then moved the rgb variables into the function. it works beautifully now. Thank you wise stackoverflow frens – bootygrocery1000 Sep 09 '22 at 21:30