Search code examples
javascripthtmlcssanimated

how do i animate another colour after this?


I have a 2x4 box using a 'div' in html and formatted in CSS. this

<body>

<div class="container">
<div class="box rightSpacing">
  <!--Box 1--->
</div>
<div class="box rightSpacing" id="green">
  <!--Box 2--->
</div>
<div class="box rightSpacing">
  <!--Box 3--->
</div>
<div class="box">
  <!--Box 4--->
</div>

<div class="box rightSpacing">
  <!--Box 5--->
</div>
<div class="box rightSpacing" id="yellow">
  <!--Box 6--->
</div>
<div class="box rightSpacing">
  <!--Box 7--->
</div>
<div class="box">
  <!--Box 8--->
</div>


</div>

</body>

i need to animate in a similar style the 'div id="green"' to a green colour directly after it for a similar length of time. This is where I need help, i'm stuck. thanks

this is the code i have already for the animation in javascript.

                lerp = function(a, b, u) {
              return (1 - u) * a + u * b;
            };


            fade = function(element, property, start, end, duration) {
              var interval = 10;
              var steps = duration / interval;
              var step_u = 1.0 / steps;
              var u = 0.0;
              var theInterval = setInterval(function() {
                if (u >= 1.0) {
                  clearInterval(theInterval)
                }
                var r = parseInt(lerp(start.r, end.r, u));
                var g = parseInt(lerp(start.g, end.g, u));
                var b = parseInt(lerp(start.b, end.b, u));
                var colorname = 'rgb(' + r + ',' + g + ',' + b + ')';
                el.style.setProperty(property, colorname);
                u += step_u;
              }, interval);
            };

            el = document.getElementById('yellow');
            property = 'background-color';
            startColor = {
              r: 255,
              g: 255,
              b: 255,
            };
            endColor = {
              r: 255,
              g: 255,
              b: 0
            };
            fade(el, 'background-color', startColor, endColor, 10);



            setTimeout(function() {
              fade(el, 'background-color', endColor, startColor, 10);
            }, 1000);
  • please bare with as i am extremely new to this!

Solution

  • You can do following way.

    el = document.getElementById('yellow');
    el1 = document.getElementById('green');
    
    setTimeout(function() {
        fade(el, 'background-color', endColor, startColor, 10);
        fade(el1, 'background-color', greeColor, startColor, 2000);
    }, 1000);
    

    And change in function

    el.style.setProperty(property, colorname);
    

    To

    element.style.setProperty(property, colorname);
    

    Working Fiddle