user4520762
user4520762

Reputation:

How change background-color with jquery animation, like a transition

I'm trying to create a function that changes the background of a div to colors that are within an array. I did the following:

Html:

<div class="background">

Css:

    .background {
        width: 500px;
        height: 500px;
        margin: 0 auto;
        background-color: #000;
    }

Javascript:

    function spectrum() {
        var time = 0;
        var colours = ['green', 'blue', 'red'];
        var hue = colours[time];


        $('.background').animate({
            backgroundColor: hue
        }, {
            duration: 1000,
            complete: function () {
                time += 1;
    spectrum();
            }
        });
    };

The problem is that I am unable to use like a recursion, it changes the background once and stops... What am I doing wrong here???

I tried to find a code ready to use, but just find CSS3, and I want to give support for IE8.

Anyone knows a good way to do what i am trying to do?

Thanks!

Upvotes: 0

Views: 2106

Answers (3)

guest271314
guest271314

Reputation: 1

The problem is that I am unable to use like a recursion, it changes the background once and stops... What am I doing wrong here???

var time = 0;

defines time as 0 at each call of spectrum, resulting in time += 1; at .animation() complete function not being applied at recursive spectrum calls.


For applying a color animation effect, try utilizing jQuery Color

function spectrum(t) {
 
      var colours = ["green", "blue", "red"];
      var time = t && t < colours.length ? t : 0;
      var hue = colours[time];

      $(".background").animate({
        backgroundColor: hue
      }, {
        easing: "linear",
        duration: 1000,
        complete: function() {
          time += 1;
          // recursively call `spectrum`,
          // with `time` as argument
          spectrum(time);
        }
      });
    };
    spectrum();
.background {
  width: 500px;
  height: 500px;
  margin: 0 auto;
  background-color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script src="https://code.jquery.com/color/jquery.color.plus-names-2.1.2.min.js">
</script>
<div class="background"></div>

Upvotes: 1

Max D
Max D

Reputation: 815

Sorry with all colors you can do this:

    function  spectrum(){
    var  mcolors = ['green', 'blue', 'red'];
    var time = 500;             
    $.each(mcolors, function(index, value){
    setTimeout( function(){ 
$('.background').css({
    transition: 'background-color 1s ease-in-out',
    "background-color": value
    }); }, time)
    time += 1000;
    });}

Upvotes: 0

Max D
Max D

Reputation: 815

Try this:

 $('.background').css({
 transition: 'background-color 1s ease-in-out',
 "background-color": "red" });

Upvotes: 1

Related Questions