4

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.

1
  • Does the element have a filter-property when first loaded? Commented Aug 14, 2019 at 12:34

2 Answers 2

3

Firstly you are setting the transition of the --webkit-filter property, but you set the filter property. Secondly as jneander mentioned the change is happening too quickly you should wrap it in a requestAnimationFrame or a timeout

Here is a working demo with the fixes:

let value = "15px";
let loadImg = document.getElementById("block");

let transitionDuration = "1s";
let timing = "ease-in-out";
let delay = "1s";

loadImg.style.filter = `blur(${value})`;
requestAnimationFrame(()=>{
  loadImg.style.transition = `filter ${transitionDuration} ${timing} ${delay}`;
  
  loadImg.style.filter = 'none';
});
#block {
  width: 150px;
  height: 150px;
  background: red;
}
<div id="block"></div>

Sign up to request clarification or add additional context in comments.

Comments

2

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.