1

I'm trying to have a functioning background color change (change in the gradient dependent on a value) be smoother and "animated". Basically I am wondering where to put the animate code as my change in color exists in different ways (with a switch)

Should it be within each case? or should it be in the function in which the switch is located?

I tried to put the code to change the color there but it doesn't seem to work.

Thanks.

document.getElementsByClassName('article-rating')[i].addEventListener('click', function() {
    sum = allSource2.reduce((tempSum, val) => tempSum + val);
    console.log(sum);

    switch (sum){
        case 1:
            document.body.style.backgroundImage.animate = "linear-gradient(45deg, #4A6ECF 0%, #B46E86 80%, #D76D6D 20%)";
        case 3:
            document.body.style.backgroundImage.animate = "linear-gradient(45deg, #4A6ECF 0%, #B46E86 20%, #D76D6D 90%)";
    }   
});
Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
Minimorum
  • 21
  • 7
  • What is `backgroundImage.animate`? I may be rusty with my newer CSS additions, but I don't think that exists. Usually what you'd do is give the element a `transition` CSS property and then just change the `backgroundImage` directly. – IceMetalPunk Mar 21 '19 at 19:17
  • @IceMetalPunk Thanks, I'm confused as where to put the transition, because of where I defined the value of the gradient. Currently they are defined in each case of the switch. Does your solution mean I would have to define each case as a CSS property in the CSS file? – Minimorum Mar 21 '19 at 19:23
  • No? The gradient can be changed at any time, it doesn't matter, but it should be on the `backgroundImage` property, not on `backgroundImage.animate`. The transition property just goes in the CSS for the element you're targeting (the body, in this case). One transition property is enough; with that set, every change in styles for that element will animate smoothly. – IceMetalPunk Mar 21 '19 at 19:25
  • oh got it! So in the css does it have to mention `background-image`? Since it's the thing I am changing in the js file. I basically wrote `transition: background-image 3s ease-in;` but testing the color change in the gradient is not smooth – Minimorum Mar 21 '19 at 19:30
  • You've done it correctly; unfortunately, it turns out that transitions don't work with gradients currently :( See here for an alternate solution: https://stackoverflow.com/a/7364325/2444210 – IceMetalPunk Mar 21 '19 at 19:51

0 Answers0