+ 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

8th Jun 2023, 6:30 PM
C. Scheler
C. Scheler - avatar
9 Respostas
+ 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
9th Jun 2023, 2:22 PM
ODLNT
ODLNT - avatar
+ 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
9th Jun 2023, 2:40 AM
Gordon
Gordon - avatar
+ 4
9th Jun 2023, 9:58 PM
ODLNT
ODLNT - avatar
9th Jun 2023, 5:20 PM
ODLNT
ODLNT - avatar
+ 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
9th Jun 2023, 2:36 PM
Bob_Li
Bob_Li - avatar
+ 1
ODLNT Thanks, it works now!
9th Jun 2023, 2:33 PM
C. Scheler
C. Scheler - avatar
0
Gordon Wouldn't it be more computationally efficient to use CSS?
9th Jun 2023, 9:44 AM
C. Scheler
C. Scheler - avatar
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;
9th Jun 2023, 9:18 PM
Bob_Li
Bob_Li - avatar
0
ODLNT now I feel that there are hair triggers all over the underlying DOM/Javascript interface.
9th Jun 2023, 10:55 PM
Bob_Li
Bob_Li - avatar