0

I often either add some HTML (for example, via insertAdjacentHTML) or set the innerHTML of some element. When this is done, I want to start a CSS transition by adding a class.

There seems to be no obvious way to determine how long I have to wait before doing this in order for the transition to work reliably.

Sometimes, a setTimeout(..., 0) seems to be enough. Sometimes, not even a delay of 100 ms is enough.

Is there some kind of event that is triggered as soon as an element is... "ready"?

Seven Systems
  • 127
  • 3
  • 13
  • just set your transition on your plain element, after you did insert it or inner anything. update CSS, It can be via style or classList.add , the transition will trigger itself. CSS rules must be there already set to 0 or its default value (numeric value) – G-Cyrillus Jan 11 '23 at 20:56
  • Can you elaborate? Because whenever I append HTML the change is instant, no need for a delay. – Reyno Jan 11 '23 at 20:56
  • Note that in most cases you're probably better of using the Web Animation API instead. – Kaiido Jan 11 '23 at 23:29
  • @Kaiido, you closed the question and gave a link to the one you answered. Web Animations API is for chaning the transitions for elements that you know is already there. OP's problem looks like he does not control when `innerHTML` will get called, thus he needs to make sure the element is there before doing anything. Does he not? – ibrahim tanyalcin Jan 12 '23 at 09:26
  • @ibrahimtanyalcin, no they face the exact same problem as in the dupe target: they try to animate an element that never got a box computed for it. See their self-answer. Yours is off. – Kaiido Jan 12 '23 at 09:29

1 Answers1

0

Querying the newly added element's offsetWidth seems to synchronously trigger a render of the element and so, doing that before applying the CSS transition seems to do the trick. All tests so far have produced the transition with 100% reliability.

Seven Systems
  • 127
  • 3
  • 13