CSS transitions don't work unless I use a timeout

I have a couple of classes: hide is display: none , and transparent - opacity: 0 . The pr_container element has -webkit-transition: opacity 1s . The following jQuery-based code makes an element rendered in animated fasion:

 pr_container.removeClass("hide"); setTimeout(function() { pr_container.removeClass("transparent"); }, 0); 

However, when I delete setTimeout and instead just delete the second class, there is no animation. Why?

Edit: I am using the latest Chrome, I have not tested other browsers yet.

Edit: I tried putting both calls in the same setTimeout callback - without animation. So it’s clear about separation.

Edit: here is jsFiddle: http://jsfiddle.net/WfAVj/

+6
source share
4 answers

You cannot make a transition if you change the display property at the same time. Therefore, to make it work, you need to hide your element in a different way. For instance:

 .hide { height: 0; width: 0; /* overflow: hidden; padding: 0; border: none; */ } 

http://jsfiddle.net/dfsq/WfAVj/1/

+3
source

There is no reasonable “ curve ” to go from one display state to another, so in the current browser implementation, any transition that somehow involves display will not have any transition at all.

With this code:

 pr_container.removeClass("hide"); pr_container.removeClass("transparent"); 

You can imagine that two statements are executed in one “blocking” queue, therefore the browser practically displays an element from class="hide transparent" to class="" , and, as indicated above, the hide class practically cancels any existing transition.

Using

 pr_container.removeClass("hide"); setTimeout(function() { pr_container.removeClass("transparent"); }, 0); 

You told the browser to remove the "transparent" class "as soon as possible, but not in the same queue", so the browser first removes the "hide", and then goes. Removing the "transparent" occurs when the browser considers that it has a supply of resources, so the transition does not become invalid.

+3
source

only the "transperent" class produces animation .. "Hide" instantly. So, start the animation and, if necessary, “hide” after 1 second:

  test.addClass("transparent"); //hide after 1 sec, when the animation is done setTimeout(function() {test.addClass("hide"); }, 1000); //1000ms = 1sec 

http://jsfiddle.net/WfAVj/4/

0
source

Using the suggestions in a related question, I made a version that I am pleased with:

 .test { -webkit-transition: visibility 1s, opacity 1s; } .hide { visibility: hidden; } .transparent { opacity: 0; } 

http://jsfiddle.net/xKgjS/

Edit: now two classes can be combined into one!

Thanks everyone!

0
source

All Articles