zaarr78 zaarr78 - 3 years ago 116
HTML Question

Restart css transition

I'm trying to restart a

transition
in
Javascript and without librairies or css
. I don't want to achieve this with a trick like
Settimeout
or
clientHeight
. I know it's because of reflow but I'm trying to find the ideal solution for this.

Here are the steps :

1)
Remove
transition -> set the new position (
without
transition)

2)
Add
transition -> set the new position (
with
animation)

Here is the Javascript.

let element1 = document.querySelector(".box")

document.querySelector("button").onclick = () => {

element1.style.transition = "none"
element1.style.transform = "translateY(50px)"

element1.style.transition = "all 0.4s";
element1.style.transform = "translateY(10px)"

}


Right now is only making the transition and moving by 10px instead of setting the 50px position first.

Answer Source

Your code don't works because the browser don't recalculates the styles between your first and second "batch" of updates.

One trick is to force the browser recalculate them by calling one of the functions that do it. I'll use getBoundingClientRect, for example, as the browser needs to calculate styles to get the size and position of the element.

So:

let element1 = document.querySelector(".box")
document.querySelector("button").onclick = () => {
  // Call the first batch of updates
  element1.style.transition = "none";
  element1.style.transform = "translateY(50px)";

  // Force the browser recalculate the styles
  element1.getBoundingClientRect();

  // Call the second batch of updates
  element1.style.transition = "all 0.4s";
  element1.style.transform = "translateY(10px)";
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download