4

What am I doing wrong that the following doesn't animate the background color?

<div style="height:100px;width:100px;background:red">animate this</div><br>
<input type="button" id="mybutton" value="start"/><br>


$("#mybutton").click(function(){
   $("div").animate({backgroundColor: 'blue'});
});

http://jsfiddle.net/bjf2L0ha/

4thSpace
  • 43,672
  • 97
  • 296
  • 475
  • possible duplicate of [jQuery animate backgroundColor](http://stackoverflow.com/questions/190560/jquery-animate-backgroundcolor) – Norbert Jul 11 '15 at 04:37

2 Answers2

9

You need to import an additional plugin such as jQuery UI in order to support color in your animate() function as jQuery alone doesn't.

$("#colorBtn").click(function() {
  $('#demodiv').animate({backgroundColor: 'blue'})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<input type="button" id="colorBtn" value="Change Color"/><br>

<div id="demodiv" style="height:100px;width:100px;background:red"></div>
dmlittle
  • 964
  • 6
  • 15
1

Try setting rgb values for css background-color property within step option of .animate()

var props = {
    from: 255,
    to: 0
  },
  div = $("div"),
  button = $("#mybutton");

button.click(function() {

  $(props).finish().animate({
    // toggle between "blue" , "red"
    from: props.from === 255 ? 0 : 255,
    to: props.to === 0 ? 255 : 0
  }, {
    easing: "linear",
    duration: 3000,
    step: function() {
      div.css("backgroundColor"
                   , "rgb(" 
                     + Math.round(this.from) 
                     + ", 0, " 
                     + Math.round(this.to) + ")");
    }
  });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div style="display:block;height:100px;width:100px;background-color:red">animate this</div>
<br>
<input type="button" id="mybutton" value="start" />
<br>
guest271314
  • 1
  • 15
  • 104
  • 177