Michał Šrajer
Michał Šrajer

Reputation: 31182

minimum interval between setting css transition

I want to set instantly some css property to some value, and then start transition from this value to different one. I need to call that several times. When I run for the first time, or I do it step-by-step on the console it works as expected, however when executed in single javascript function it does not work unless I force some delay using setTimeout.

Running on the console line-by-line works, but called all at once doesn't:

el.style.transition = ''; // no transition from now
el.style.left = '50px'; // set instantly to 50
el.style.transition = '1s'; // 1s transition from now
el.style.left = '250px'; // animate from 50 to 250

Here is the jsfiddle demo.

So, the question is - how do I update css transition, to make sure it will work, and/or when I update css transition how do I know if/when it's started to affect other properties I would like to animate?

Update:

From my tests, is seems like setting transition property works somehow asynchronously, but I cannot find any way to set callback for its change.

Upvotes: 3

Views: 989

Answers (2)

Michał Šrajer
Michał Šrajer

Reputation: 31182

I got the solution (http://jsfiddle.net/9wsrv0mg/9/).

The trick is to read some DOM property which will force browser js and rendering thread to sync.

So, this will work:

el.style.transition = '';
el.style.left='50px';
var tmp = el.offsetLeft; // HERE COMES THE MAGIC - reading this prop forces delay we need
el.style.transition = 'left 1s';
el.style.left='250px';

Upvotes: 2

RichieAHB
RichieAHB

Reputation: 2088

Set the transition to:

el.style.transition="left 1s linear 1s".

You need to use the CSS3 transition-delay property, but you can set this in the broader transition property that you used. This allows a few transition options to be set, the fourth of which is the delay time.

Formal syntax: [ none | < single-transition-property > ] || < time > || < timing-function > || < time

See this fiddle. It appears initially you need a slight delay for the transition not to act on the previous style change. There is no callback for a style property change so you just need to force the update of the transition element into the next browser event loop. It's been noted in this answer too.

el.style.transition = 'left 0s linear 0s'; // no transition from now
el.style.left = '50px'; // set instantly to 50
setTimeout(function(){
    el.style.transition = 'left 1s linear 1s'; // 1s transition from now
    el.style.left = '250px'; // set instantly to 50
}, 0);

Upvotes: 1

Related Questions