pmath325
pmath325

Reputation: 61

How do I change the color of my background 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 that is the newColor() function...

When the button clicks, I'd like it to smoothly transition into the next quote as opposed to abruptly loading it. I'd also like for the quote to fade into white and then into a new quote... How is this achieved? Is it better to use jQuery?

Thanks!

Upvotes: 3

Views: 726

Answers (3)

Dan Philip Bejoy
Dan Philip Bejoy

Reputation: 4391

Add transition to your body for background-color property.

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

To add transition to any element you should write,

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

For heading tags it will be

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

Transition only works when there is a change in the CSS property specified for the given element.

Upvotes: 2

Owen Glen
Owen Glen

Reputation: 66

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

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

Upvotes: 1

mika
mika

Reputation: 1451

Keep your code as is and add a css property:

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

Or with JS:

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

Upvotes: 0

Related Questions