-1

I've set up a web page which changes the background color of the body after every 2 seconds. What I've been struggling with is how to integrate transition effect into the setInterval method. I want the new colors to appear with a fade effect, just like the transition property does in CSS. How can I achieve this effect for these changing/switching background colors?

Here's my code:

var startButton = document.getElementById("startButton");
var body = document.getElementById("body");

// Click Event Listener
startButton.addEventListener("click", function() {
  setInterval(function() {
    body.style.backgroundColor = generateRandomColors();
  }, 2000);
});


// GENERATE Random Colors
function generateRandomColors() {
  var arr = [];
  arr.push(pickRandomColor());
  return arr;
}

// PICK Random Color
function pickRandomColor() {
  // Red
  var r = Math.floor(Math.random() * 256);
  // Green
  var g = Math.floor(Math.random() * 256);
  // Blue
  var b = Math.floor(Math.random() * 256);
  // RGB
  var rgb = "rgb(" + r + ", " + g + ", " + b + ")";
  return rgb;
}
<html>
<body id="body">
  <button id="startButton">Start</button>
</body>
</html>
Satpal
  • 132,252
  • 13
  • 159
  • 168

1 Answers1

2

Set the transition property specifying which property you want to transition and how long it will take.

var startButton = document.getElementById("startButton");
var body = document.getElementById("body");

// Click Event Listener
startButton.addEventListener("click", function() {
  setInterval(function() {
    body.style.backgroundColor = generateRandomColors();
  }, 2000);
});


// GENERATE Random Colors
function generateRandomColors() {
  var arr = [];
  arr.push(pickRandomColor());
  return arr;
}

// PICK Random Color
function pickRandomColor() {
  // Red
  var r = Math.floor(Math.random() * 256);
  // Green
  var g = Math.floor(Math.random() * 256);
  // Blue
  var b = Math.floor(Math.random() * 256);
  // RGB
  var rgb = "rgb(" + r + ", " + g + ", " + b + ")";
  return rgb;
}
body { transition: background-color 2s; }
<html>
<body id="body">
  <button id="startButton">Start</button>
</body>
</html>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335