"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why does my CSS transition not start or trigger the callback function, and how can I fix it using a setTimeout?

Why does my CSS transition not start or trigger the callback function, and how can I fix it using a setTimeout?

Published on 2024-11-03
Browse:313

Why does my CSS transition not start or trigger the callback function, and how can I fix it using a setTimeout?

CSS Transition Not Starting or Callback Not Invoked

Problem Summary

An HTML element's position is updated using CSS transitions. However, the transition fails to trigger or the callback function is not invoked despite adding a transition transitionend event listener. This issue can be solved by wrapping the change with a setTimeout(1ms).

Solution Explanation

The reason behind this behavior lies in the browser's rendering process. Before the browser can apply the CSS transition, it must first apply the inline styles to the element. If the element is not yet in the DOM, its computed style display is set to "".

When the new style is set, the browser has not yet applied the inline style. Therefore, the element's computed style remains as "", with its left and top values still at 0px.

Consequently, when the transition property is applied before the next frame paint, the left and top values are already the desired ones, resulting in no transition to perform and no triggering of the transitionend event.

To resolve this issue, a reflow can be forced using the Element.offsetHeight getter or other DOM methods that require up-to-date styles. This forces the browser to update the styles before applying the transition, ensuring a smooth implementation.

Example

The following code demonstrates the issue and its workaround:

document.body.innerHTML  = tablehtml;

var animdiv = document.getElementById('spanky');
animdiv.addEventListener("transitionend", function(event) {
  animdiv.style.backgroundColor = 'red';
}, false);

// force a reflow
animdiv.offsetTop;

animdiv.style.backgroundColor = 'green';
Object.assign(animdiv.style, {
  left: "100px",
  top: "100px"
});

In this example, the animdiv element's offsetTop getter is used to force a reflow before its position is updated. This ensures that the CSS transition properly triggers and the callback function is invoked.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3