How do I change my background color smoothly?

Here is the code in question - https://codepen.io/illpill/pen/VbeVEq

function newColor() {
    var randomNumber = Math.floor(Math.random() * (colors.length));
    document.body.style.backgroundColor = colors[randomNumber];
}

      

Right now this is the newColor () function ...

When the button is clicked, I would like it to move smoothly to the next quote rather than fast loading it. I would also like the quote to fade to white and then to a new quote ... How is this achieved? Is it better to use jQuery?

Thank!

+3


source to share


3 answers


Add a transition to your body for the property background-color

.

body {
  transition : background-color 1s ease-in-out;
}

      

To add a transition to any element you have to write,

element-selector {
  transition: [CSS property] [duration] [timing-function];
}

      



For tag headers it will be

h3,h4 {
  transition: [css property] [duration] [timing-function]
}

      

The transition occurs only when the CSS property set for this element changes.

+2


source


You can use CSS to fade out the background (as shown in the image below), but you have to use JavaScript to fade out the text. Here's a working version with the quote and author fading out between random states:



$('#quote').fadeOut(400,function(){
  $(this).html(quotes[randomNumber][0]).fadeIn();  
});
$('#author').fadeOut(400,function(){
  $(this).html(quotes[randomNumber][1]).fadeIn();  
});

      

+1


source


Save your code as it is and add the css property:

.your-element-selector {
  transition: all ease 500ms;
}

      

Or with JS:

document.body.style.transition = 'all ease 500ms';

      

0


source







All Articles