CSS transition not animating when resizing immediately with JavaScript

When setting the element height to 0 in JavaScript and then changing it to a certain value, the CSS transition for the element does not work.

However, setting the code to increase the height inside setTimeout() , even with a delay of 0, the transition works, as you can see in the following fragment:

 // Doesn't work: document.getElementById("one").setAttribute("style", "height: 0px"); document.getElementById("one").setAttribute("style", "height: 200px"); // Works: document.getElementById("two").setAttribute("style", "height: 0px"); setTimeout(function() { document.getElementById("two").setAttribute("style", "height: 200px"); }, 0); 
 div { display: inline-block; width: 200px; background-color: black; transition: height 1s; } #two { background-color: blue; } 
 <div id="one"> </div> <div id="two"> </div> 

This behavior is consistent across all major browsers. The problem with this is that sometimes there is some lag, which makes the workaround not animated. Thus, this does not seem to be a clean solution.

What causes the transition to cancel and how can I get around this cleanly?

+6
source share
3 answers

Most likely, browsers will optimize transitions and will combine changes that take less than 16 ms (which will give you an update rate of about 60 frames per second)

So, the solution is to simply transfer the style changes to nested RAF calls (tell the browser the animation when it is ready, and not after an arbitrary timeout)

 window.requestAnimationFrame(function(){ document.getElementById("two").setAttribute("style", "height: 0px"); window.requestAnimationFrame(function(){ document.getElementById("two").setAttribute("style", "height: 200px"); }); }); 

link: https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame

+4
source

Try adding it to the window.onload event

 window.addEventListener("load", init, false); function init() { document.getElementById("one").style.height = "200px"; } 

also you need to set the #one height in CSS to 0

 #one { height:0px; } 
0
source
 //cache the object in a variable var one = document.getElementById("one"); //do you really need to overwrite all stlyles defined on this object? //if not, prefer style-property over attribute //set animation-start one.style.height = 0; //force the browser to apply styles getComputedStyles(one); //apply the animation-target one.style.height = "200px"; 

You do not need a timeout, but be careful, this causes the browser to turn into a rendering cycle (one of the most expensive things that could be done in JS).

Therefore, do not use this in a loop (or on multiple nodes, one after the other). But instead, make two loops, first set all the initial values, force the browser into the rendering loop, and then apply all the target values.

0
source

Source: https://habr.com/ru/post/1013661/


All Articles