Jnewbie
Jnewbie

Reputation: 163

How change css using variables to make an animation

How can I transition CSS values using JavaScript? I made this code, but it isn't working:

var num = 100;
function fillDiv{
var a=document.getElementById("principal");
for (var i = 0; i<100; i++){
    num=num-25;
    a.style.background="-moz-radial-gradient(#FFFFFF "+num+"%, #006699 200%);";
    if (num==0){
       break;
    }
 }

In the debug window all gone good, but when I check it on elements tag the value hasn't changed.

Upvotes: 1

Views: 592

Answers (1)

Mi-Creativity
Mi-Creativity

Reputation: 9654

As explained in comments, the for loop is too quick to notice the effect, Instead you may use interval, set the interval period to 40 this is like 25 frames per second, also made the step 10 instead of 4 in num = num - 10; so that the animation will look smooth and noticeable like below:

JS Fiddle

var num = 100;

var $interval = setInterval(function() {
  var a = document.getElementById("principal");
  num = num - 10;
  if (num >= 0) {
    a.style.background = '-moz-radial-gradient(#FFF ' + num + '%,#1e69de 200%)';
    a.style.background = '-webkit-radial-gradient(#FFF ' + num + '%,#1e69de 200%)';
    a.style.background = 'radial-gradient(#FFF ' + num + '%,#1e69de 200%)';
  } else {
    clearInterval($interval);
  }
}, 40);
body {
  margin: 0;
  padding: 0;
}
#principal {
  width: 100vw;
  height: 100vh;
  display: block;
  background-color: #1e69de;
  margin: 0 auto;
}
<div id="principal"></div>

Upvotes: 2

Related Questions