ronlaniado
ronlaniado

Reputation: 39

Animating my html element to a different background color.

I would like to make my html element change into a different background color, but I want it to have a fading transition.

    function changeBackground() {
  console.log("changeBackground() function is working");
  var backgrounds = ["navy", "blue", "aqua", "teal", "olive", "green", "lime", "yellow", "orange", "red", "maroon", "fuchsia", "purple"];
  var randomBG = backgrounds[Math.floor(Math.random() * backgrounds.length)];
  $("html").animate({backgroundColor: randomBG}, "slow");
  console.log(randomBG);
}

I'm having some trouble on the 5th line. Something here isn't working, and my code is breaking. Is this the correct way to do this/should I be using fadeIn() (and how)?

Upvotes: 0

Views: 77

Answers (1)

Sergey
Sergey

Reputation: 7682

According to description of animate method

Properties that can be animated:

backgroundPositionX
backgroundPositionY
borderWidth
borderBottomWidth
borderLeftWidth
borderRightWidth
borderTopWidth
borderSpacing
margin
marginBottom
marginLeft
marginRight
marginTop
outlineWidth
padding
paddingBottom
paddingLeft
paddingRight
paddingTop
height
width
maxHeight
maxWidth
minHeight
minWidth
fontSize
bottom
left
right
top
letterSpacing
wordSpacing
lineHeight
textIndent

So, background-color cannot be animated. However you can appoint the transition property for element you need. Then you can change the colour of your element it will be animated with browser built-in animation.

Like that

function changeBackground() {
  console.log("changeBackground() function is working");
  var backgrounds = ["navy", "blue", "aqua", "teal", "olive", "green", "lime", "yellow", "orange", "red", "maroon", "fuchsia", "purple"];
  var randomBG = backgrounds[Math.floor(Math.random() * backgrounds.length)];
  $("html").css('background-color',randomBG);}
  
 $('#click').click(function () {changeBackground()});
html {
  transition: background-color 5s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="click">Click to change the colour</button>

Upvotes: 1

Related Questions