JQuery .animate() background color not working

I’m a beginner trying to figure out how to transition background colors. I’ve added JQuery and JQuery UI, but I am still unable to change background colors. Here’s a link to my codepen:

The problem is that you hard-coded what color the container will have after clicking the button. You may want to create a function that generates a random color.

Now there are many ways to do that. One approach is to keep in mind that each color component takes an integer from 0 to 255. Then you can generate three random integers and create a valid CSS value for background-color.

// this should return a string that looks like `rgb(0,0,0)`
function randomColor() {
  const red = ...
  const green = ...
  const blue = ...

  return 'rgb(' + ... + ')';
}

// ...

$('#quote-container').css({'background-color': randomColor()});

Thanks for responding so quickly! I still cannot get the animate function to work. I understand how to create the random color function, and how to change colors through .css(). From what I understand, .animate() should work as long as you’ve added both JQuery and JQuery UI, unless I am missing something? I would like to transition colors more smoothly than simply using .css(). I know there are other options to do that , but would like to figure out why this method isn’t working. Updated pen:

Thanks!

According to the docs, you can’t animate backgroundColor because it’s not a single numeric value. (see https://api.jquery.com/animate/, under “Animation Properties and Values”)

You can try the jQuery.color plugin.

You can also use .css instead of .animate, then give the body transitions in the CSS.

body {
  transition: background-color ease-in 1s; /* tweak to your liking */
}
$('body').css({'background-color': randomColor()});

Thanks, the body transitions are probably what I will end up doing! I am still extremely confused because the jQuery UI docs show that it should work. I believe jQuery UI adds the jQuery.color plugin (see https://api.jqueryui.com/color-animation/). I have added both jQuery and jQuery UI to my pen. I’m fine using another method to create the transitions, but I at least want to understand where I am going wrong.

Didn’t know you could do that with jQuery UI. It does work, but you need to put jQuery before jQuery UI in the JS settings.

1 Like

Ah, I see. It works now thanks a bunch.