+ 3
[solved] CSS transition doesn't work on newly created element
I have a code where I create an HTML element using JavaScript and then set the height to 100px (after writing "height:0; transition:height 0.5s" in CSS). The problem is that the height is set to 100px instantaneously without gradually transitioning. I know that this can be fixed by using setTimeout in JavaScript to set the height. However, once I put the code in an interval (I need new elements to be created regularly), it stops working again. This, too, can be fixed by increasing the duration of the timeout. But the shorter the duration is, the less likely it is to work. Is there a way to do this without using long timeouts? https://code.sololearn.com/WFVz3PUpJc9y/?ref=app
9 Réponses
+ 5
The issue might be related to how the browser handles rendering and JavaScript events. To fix it, you can force the browser to recalculate the styles before applying the transition by triggering a reflow, which can be done by accessing a property that requires layout calculations on the element, offsetHeight for example, before modifying its style.
let h = document.createElement("div");
document.body.appendChild(h);
h.offsetHeight// will trigger reflow
h.style.height = "100px";
Reflow - Reflow happens when a browser must process and draw part or all of a webpage again, such as after an update on an interactive site. MDN
+ 4
May I suggest using JavaScript to increment the height?
When it comes to rendering, requestAnimationFrame is preferred to setInterval and setTimeout.
Here is my edits in your code snippet for demonstration:
https://code.sololearn.com/WfWmXJNf2UZ7/?ref=app
+ 4
Here is a more comprehensive list.
https://gist.github.com/paulirish/5d52fb081b3570c81e3a
+ 3
I forgot to add this reference.
https://semisignal.com/triggering-reflow-for-css3-transitions/
+ 2
ODLNT
Fantastic.
That's a new one for me, too.
These are things you never learn from textbooks.
a little demo to celebrate the clever solution.🎇🎆
https://code.sololearn.com/WKF8iMcVNc55/?ref=app
+ 1
ODLNT Thanks, it works now!
0
Gordon Wouldn't it be more computationally efficient to use CSS?
0
ODLNT
That link was suggesting offsetWidth. .
Yes, it's another solution.
Following related links, these are the alternative solutions:
h.offsetHeight;
h.offsetWidth;
h.clientHeight
h.clientWidth;
h.scrollHeight;
h.scrollWidth;
0
ODLNT
now I feel that there are hair triggers all over the underlying DOM/Javascript interface.