Random Quote Generator — Background color animation

Help! I am almost done with the Random Quote Generator project, but I can’t figure out how to get the background color to change randomly and the text to fade in and out like in the project example. Any help would be much appreciated!

Are you using React?

This is what I did:

In the top I declare a object with the colors:

const colorObj = {
'0': "#16a085",
'1': "#27ae60",
'2': "#2c3e50",
'3': "#f39c12",
'4': "#e74c3c",
'5': "#9b59b6",
'6': "#FB6964",
'7': "#342224",
'8': "#472E32",
'9': "#BDBB99",
'10': "#77B1A9",
'11': "#73A857"

Then, with this I generate a random number between 0 and 11:

 var colorRand = Math.round(Math.random() * (11 - 0)) + 0;

Then, with each click to generate a random quote I change the backgroundColor with the value in


Then I put the value in colorRand in the color state.

this.setState({color: colorRand});

The value in the state I used after the render method, like this:

document.body.style.background = colorObj[this.state.color];

The effect of changing the background is achieved in this way:

 transition: background 1s;

The text effect I don’t remember very well how I did it, but it works more or less like this:

if(this.state.opacity == 1){
  this.setState({opacity: 0}); //each click sets the opacity to 0

//a lot of code

//set a setTimeout to 500 to wait half a second after clicking 
//to return the opacity to 1 and give it the fade effect
if(this.state.opacity == 1){ // I don't remember what this was for
   this.setState({opacity: 0});
 if(this.state.opacity == 0){
    this.setState({opacity: 1});

I created that code a long time ago, and now that I see it I could do it differently, but it has the expected effect :smiley:

You can look my code: https://codepen.io/gtaypeg/pen/povVOVW

Thank you! It worked :slight_smile: :smiley:

I can see this problems have been sloved
I just come here ,hope can study . thanks
I give you a example:
this is image background ,can the 100% the phone and PC
last code is right ,

One small suggestion for future proofing. This line of code here:

 var colorRand = Math.round(Math.random() * (11 - 0)) + 0;

Can be changed to:

var colorRand = Math.floor(Math.random() * colorObj.keys().length);

Using the length of the keys array instead of a hard-coded number means that if you decide to add or remove colors later on, you don’t need to edit the code outside of colorObj.

And using Math.random in combination with Math.floor means that it will always round down to the nearest integer, meaning that you don’t run the risk of generating an index that falls outside of the color count.

1 Like