1

I'm trying to do something like this:

element.classList.add('animate-in')
element.style.transform = 'translateY(100px)';

Where the animate-in class has a transition: transform 1s property for animation. But when I run this it the element is translated 100px down but without the transition, seems like the transform property is modified before the class name can be added and take affect. I don't want to use setTimeout since it can be unreliable in animations. Is there any way to wait for the class to be added before modifying any styles?

3 Answers3

0

I don't think we get any events for the 'application of styles' through JavaScript, which is pretty frustrating in this case...

I found this thread that's pretty helpful.

One thing to note: the animation will work even if you use setTimeout with 0 ms. What was the reason in particular that it messed with animations?

setTimeout(function(){
    element.style.transform = 'translateY(100px)'
}, 0)

Also, if you set it up with an event, you can change the style directly and see the animation applied.

Here's the bin I was playing around with: https://jsbin.com/lofotutumu/edit?html,css,js,output

Daniel Thompson
  • 2,193
  • 4
  • 23
  • 37
0

You don't really want to wait, but want the properties embedded with this new class to be applied.

And this can be done, synchronously, by triggering a reflow.

Some properties/functions need the DOM boxes to be recalculated in order to return their values. To do so, the browser has to trigger a reflow on the page, and hence will apply your new properties.

But note that this has a performance impact, particularly on complex pages, so use it with care.

element.classList.add('animate-in');
element.offsetTop; // trigger a reflow
element.style.transform = 'translateY(100px)';
.animate-in {
  transition: transform 2s linear;
}
<div id="element">Hello</div>
Kaiido
  • 123,334
  • 13
  • 219
  • 285
0

Would creating a keyframe and adding that into your class suit your needs? E.g.

// This is your keyframe to animate your element
@keyframes translateDown {
    0%{
        transform:translateY(0);
    }
    100%{
        transform:translateY(100px);
    }
}

.animate-in{
    animation: 2s linear translateDown both;
}
connoraworden
  • 581
  • 3
  • 12