1

I just have a div with the background color covering the entire view called "colorPanel" (using html id).

This code does not run and I don't understand why.

When I change col to $col, it still does not run.

What am I not understanding about jquery?

function animateColors(i){
    var val = 1/0.2*(i) * 210;
    var col = 'hsla('+val+', 90%, 60%, 1)';
    $("#colorPanel").animate({"background-color": col}, 200);
    i = (i<180)? i+4 : 0;
    animateColors(i);
}

animateColors();
2
  • 1
    You arent passing anything to the initial call to animateColors(). Is this a typeo? If not i is undefined for the initial run of the program. Also there is no terminating condition for your recursive function. Commented May 2, 2016 at 3:07
  • 2
    From the documentation, "The .animate() method allows us to create animation effects on any numeric CSS property." and "For example, width, height, or left can be animated but background-color cannot be, unless the jQuery.Color plugin is used". Depending on your requirements, you could just use a CSS transition. Commented May 2, 2016 at 3:07

1 Answer 1

2

Already @brut & @tiantang suggest the valid point as comment. please consider that.

You arent passing anything to the initial call to animateColors(). Is this a typeo? If not i is undefined for the initial run of the program. Also there is no terminating condition for your recursive function.

From the documentation, "The .animate() method allows us to create animation effects on any numeric CSS property." and "For example, width, height, or left can be animated but background-color cannot be, unless the jQuery.Color plugin is used". Depending on your requirements, you could just use a CSS transition.

As per those comments I will make changes on your code.

$(document).ready(function(){
    function animateColors(i){
        var val = 1/0.2*(i) * 210;
        var col = 'hsla('+val+', 90%, 60%, 1)';
        $("#colorPanel").css({"background-color": col});
        i = (i<180)? i+4 : 0;
        // animateColors(i); // when using this too much recursion error occur
        setTimeout( function(){animateColors(i)}, 500);
    }
    animateColors(1);
});
#colorPanel {
  height: 20px; /*your wish*/
  width: 100%; /*your wish*/
  transition: all ease 0.5s; /*for animation effect*/
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="colorPanel"></div>

I hope this will help you.

Sign up to request clarification or add additional context in comments.

1 Comment

This will work! Thank you. I did not realize you could not run random jquery lines in javascript without document ready. I will look for into how jquery works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.