Samul
Samul

Reputation: 2019

CSS Transition with jquery does not look to work as expected

I have a div and I want it to make a transition from font-size 20px to font-size 40px and also change its color. I know I can make this with maaany other alternativas, but I want to explore the usage of "transition" and I think something is wrong.

If I do this:

$("#xxx").css({transition:"all 1500ms ease-out 0ms",color:"#00FFFF", fontSize:"40px"});

The jQuery should first set the "transition", and after that set the color and font-size AND THE BROWSER should make the transition. But it's not the case, the font-size and color are applied immediatly.

What is even strange is that if I first set the transition and after 2 seconds set the font-size and color, then the transition will happen smoothly. Why?

Check the example below. If you open the link the browser will apply the color and font-size immediatly, instead of making the transition smootly. Why?

https://jsfiddle.net/hw33bghm/

Upvotes: 0

Views: 58

Answers (1)

Brad Colthurst
Brad Colthurst

Reputation: 2605

The reason why this isn't behaving in the way that you expect is due to how reflow works in the DOM. Reflow is the web browser process for re-calculating the positions and geometries of elements in the DOM, and can be triggered by many things, including in this case, adjusting the CSS properties of an element.

When you make the $("#xxx").css({...}); call with multiple CSS properties you are giving the browser a batch of layout operations to perform and it will perform all of them in a user-blocking manner. Your styles are being applied immediately because there is no transition property until the operation is done and your new DOM is rendered.

Further, all modern browsers have optimizations to minimize reflow (again, it's a blocking operation and as such can affect performance), so if you simply separated setting your properties:

$("#xxx").css({transition:"all 1500ms ease-out 0ms"});

$("#xxx").css({color:"#00FFFF", fontSize:"40px"});

You might expect it to set the transition property, reflow, then set the color and fontSize, triggering the transition and working the way you intended. It won't though, those operations will be batched by the browser and again everything will happen in a single reflow.

This is also why it does work when you wait a second before setting the color and fontSize. Those layout operations are no longer batched together and so this time you have a transition property when the CSS for the other two are set.

For a little more information check out: https://developers.google.com/speed/articles/reflow#guidelines

Upvotes: 2

Related Questions