JavaScript / CSS: Delay between adding an element to the DOM and its CSS rules?

I use JavaScript to dynamically add an element to the DOM. I want to use CSS3 transitions to β€œfade” an element as it is added.

For this, I use something like the following:

function add(el) { el.className += ' fader'; el.style.opacity = 0; document.getElementById('parent-element').appendChild(el); //setTimeout(function () { el.style.opacity = 1; }, 5); el.style.opacity = 1; } 

And CSS:

 .fader { -webkit-transition: opacity 0.5s; } 

This does not work as expected - the element does not disappear. If I replace the line el.style.opacity = 1; on setTimeout(function () { el.style.opacity = 1; }, 5); as seen above, it works as expected.

I assume that the first case does not work, as there is some delay between adding an element and the corresponding CSS rules that apply to it. The 5 ms delay created by setTimeout in the second case gives enough time to apply these rules, so the attenuation occurs as expected.

Firstly, is this a correct assumption? Secondly, is there a better way to solve this problem? setTimout looks like a hack. Is it possible for some event that is fired after an element has used all its styles?

+4
source share
1 answer

To get CSS3 working, an object must exist in a certain state, and then you must make changes to the object that starts the transition.

For many reasons, all my experience with CSS3 transitions has shown me that the state that counts on this is only the state in which it exists when your javascript returns and the browser returns to the event loop. This is as if the only way that the browser can now loop over your object and remember its state for future transitions is to return to the browser events loop. There are some programming reasons why this may be so (therefore, it does not try to make transitions, since you programmatically create your object and change it), but these problems could be solved differently (for example, using a special method call to encode the object now) but it was not done that way.

So your solution is how I found this. Create an object in this initial state. Set the timer to a very short duration. Return from your javascript so that the object is codified in its original state, so the timer may fire. In the timer event, add a class to the object that triggers the CSS3 transition.

I don’t know if CSS3 transitions are really defined in this way in the specification, but my experience with Safari, Firefox, and Chrome was that this is how they work.

+3
source

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


All Articles