'How to change CSS property by JS and use transition?

I am setting up a CSS effect in JavaScript (filter property) and in the next line I am setting up that property to none. My image has filter equal to none, but I want to make it with transition.

Without the last line (when I’m setting the property back to none) if I disable the filter property in the console it works with transition.

loadImg.style.filter = `blur(${value})`;
loadImg.style.transition = `-webkit-filter ${transitionDuration} ${timing} ${delay}`;
loadImg.style.filter = 'none';

I know it’s because of JavaScript, but I have no idea how to make it work with transition.



Solution 1:[1]

The application of filter = 'none' is likely happening too quickly to allow for the initial filter value to be applied and rendered. If you wrap the second transition in a double- requestAnimationFrame, that will allow the renderer to establish the initial blur state to transition away from.

const loadImg = document.querySelector('.loadImg')

const value = '20px'
const transitionDuration = '1s'
const timing = 'linear'
const delay = '0s'

loadImg.style.filter = `blur(${value})`;

requestAnimationFrame(() => {
  requestAnimationFrame(() => {
    loadImg.style.transition = `-webkit-filter ${transitionDuration} ${timing} ${delay}`;
    loadImg.style.filter = 'none';  
  })
})

For more information on the double-requestAnimationFrame: How does double requestAnimationFrame work?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1