Aidan Young
Aidan Young

Reputation: 614

Javascript gradually change the saturation

I have some code so that when the key c is pressed, the saturation will increase and when the key c is lifted, it will revert back to normal. I'm wondering how I can make it so that instead of instantly changing the saturation level, the saturation will gradually change throughout the course of half a second and when the key c is lifted, the saturation will gradually decrease throughout a half second back to the normal saturation level. How can this be done? Current code:

document.addEventListener("keydown", e => {
  if (e.code === "KeyC") {
document.body.style.filter = "saturate(1.7)";

    
    
    
    }
}, false)

document.addEventListener("keyup", e => {
  if (e.code === "KeyC") {
  document.body.style.filter = "";

  
  }
}, false)

Upvotes: 1

Views: 183

Answers (1)

Martin Nester
Martin Nester

Reputation: 143

I would use use a CSS transition to get the gradual change. Then instead of setting the saturate value with javascript you can just do .classList.add('saturated') and .classList.remove('saturated') on the element. I made an example with a div:

#myDiv{
  width:200px;
  height:200px;
  background-color: lightblue;
  filter: saturate(1);
  transition: filter 1s ease;
}

#myDiv.saturated {
  filter: saturate(4);
}

here is a working example on JSFiddle: https://jsfiddle.net/martinnester/07fsL2ge/20/

Upvotes: 2

Related Questions