Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS3 transition doesn't work when I remove class of newly created element

What I do:

  1. Create an element, which style contains a CSS3-transition.
  2. Add a class to it (style for this class contains background-color property).
  3. Add an innerHTML to it.
  4. Remove the class.

When I remove the class just like

element.classList.remove('classname')

there are no transition, but when I set a timeout with 0s delay, it works:

setTimeout(function() { element.classList.remove('classname'); }, 0);

Why? How can I avoid setTimeout function or is it normal to use it?

Example: http://jsfiddle.net/JHevJ/1/

like image 698
isqua Avatar asked Dec 06 '25 15:12

isqua


1 Answers

Because you're removing the class before the screen calculates the redrawing of elements. You're removing it before it's shown as that class in the first place, so it doesn't think an animation is necessary.

The timeout makes it so it "waits" 0 milliseconds and then removes the class, which lets it show the element with the class first, "wait" 0 time and then remove the class.

like image 106
casraf Avatar answered Dec 08 '25 04:12

casraf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!