Home > Mobile >  How do I know when a HTML element is ready to start a CSS transition?
How do I know when a HTML element is ready to start a CSS transition?

Time:01-12

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"?

CodePudding user response:

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.

CodePudding user response:

If the class you want to add is not inside the style attribute of the innerHTML string, then you can use MutationObserver. This is an overkill but I am leaving it here anyway. Attach it to the outermost parent so you can see the changes.

!function(){
  window.addEventListener("DOMContentLoaded", function(){
     const parent = document.getElementById("parent"),
           cb =  function (mList, obs) {
              [...mList]
              .filter(d => d.type = "childList")
              .forEach(d => {
                  //console.log("Child added or removed!");
                  if (d.addedNodes.length){
                    d.addedNodes.forEach(dd => dd.classList.add("whatever"))
                  }
              })
          },
          mut = new MutationObserver(cb).observe(parent, {childList: true, subtree: true});
  })
}()
#parent *.whatever {
   transition: all 1s ease;
   background-color: red;
}
<div id="parent"><div>

Select the parent from developer console so it is assigned to $0, then do:

$0.innerHTML = `<div>haha</div>`

background should be red and whatever class added to div with textContent haha.

  • Related