Sempervivum Sempervivum - 6 months ago 18
Javascript Question

CSS transition takes final state immediately

I have a problem starting a CSS transition automatically. Commonly this is done by adding a class to the element being animated. I'm creating my elements dynamically by jQuery. When adding the class immediately after creating the element it takes it's final state immediately without transition. It works only when I add a short delay. Not very nice, can this be done in a different way?



function startbullet() {
var bullet = $('<div class="bullet"></div>');
$("#wrapper").append(bullet);
setTimeout(function () { bullet.addClass("animate"); }, 10);
}
setInterval(startbullet, 2000);

#wrapper {
height: 400px;
position: relative;
}
.bullet {
position: absolute;
top: 10px;
left: 10px;
width: 20px;
height: 20px;
background-color: #0ff;
border-radius: 10px;
transition-duration: 5s;
transition-timing-function: linear;
}
.bullet.animate {
top: 150px;
left: 400px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="wrapper">
</div> <!-- end wrapper -->




Answer

Use jQuery.animate just before adding class

function startbullet() {
  var bullet = $('<div class="bullet"></div>');
  $("#wrapper").append(bullet);
  bullet.animate().addClass("animate");
}
setInterval(startbullet, 2000);
 #wrapper {
   height: 400px;
   position: relative;
 }
 .bullet {
   position: absolute;
   top: 10px;
   left: 10px;
   width: 20px;
   height: 20px;
   background-color: #0ff;
   border-radius: 10px;
   transition-duration: 5s;
   transition-timing-function: linear;
 }
 .bullet.animate {
   top: 150px;
   left: 400px;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
</div>