0

I have a script that applies certain css styles to an element, then adds a transition style to the element, and then applies another css style to that element. What I'm trying to do is have the element get styles applied to it instantly, and then animate the next change. The code is basic, just set styles, then set transition styles, then set the final styles. But I'm experiencing that the first property being changed (the one without the transition) is having a transition applied to it, even though I do not set the transition property until afterwards. I have double checked that the element does not already have a transition property applied to it. Why is this?

Also, If I leave a 50 millisecond delay between applying the first styles and the transition, it works as expected.

markasoftware
  • 12,292
  • 8
  • 41
  • 69

1 Answers1

2

You have to force a relayout after the first styles are applied (so they are processed without transitions) and then you can apply the styles that lead to a transition. The way you are doing it now, all the opeartions are being collapsed into one operation and thus everything is undergoing the transitions.

The simplest way to get the relayout is to apply the first CSS properties, then do a setTimeout(fn, 1) to apply the second set of properties in the timer callback. There are also other ways to force a relayout by requesting certain properties that trigger a relayout. I don't remember exactly which properties those are off the top of my head (would take some research).

I haven't tried this myself, but I think requesting a size property on your element such as .offsetHeight will force the relayout. The browser realizes that there are pending style changes and that those pending style changes might affect the size request so it does a relayout synchronously before returning the .offsetHeight value, thus solving your issue.

A somewhat similar question and answer: "Force Reflow" in CSS transitions in Bootstrap

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979