Search code examples
javascriptcssweb-animations

Web Animation, how to animate the background rgba color


I want to animate the background color in rgba for a modal so it fades in. I cant use opacity as the div inside the modal I dont want to be transparent. I cant use Jquery but I am using React.

I'm not getting an error by the below does not work

const modal = document.getElementById('modal');
modal.animate(
[
  {backgroundColor: 'rgba(255, 0, 0, 0)'}, 
  {backgroundColor: 'rgba(255, 0, 0, 0.8)'}
], 
  {duration: 200, easing: 'ease-in-out', fill: 'forwards'}
);

Solution

  • Use setInterval function to change color in javascript.

    var change=0;
    var colorEvent= setInterval("changeColor();", 50);
    function changeColor(){
      if(change<100){           
          document.getElementById("modal").style.backgroundColor="rgb(255,0,"+change+")";
      }
      else 
        clearInterval(colorEvent);
      change+=1;
      console.log(change);
    }
    #modal{
        height:50px;
        background-color:rgb(255,0,0);
    }
    <div id="modal"></div>

    or changing opacity

    var change=0.0;
    if(change<0.8){
      setInterval(function(){
          document.getElementById("modal").style.backgroundColor="rgb(255,0,0,"+change+")";
          change+=0.01;
      }, 10);
    }
    #modal{
        height:50px;
        background-color:rgb(255,0,0,0);
    }
    <div id="modal"></div>