doğukan
doğukan

Reputation: 27531

Override "animation-fill-mode: forwards" by adding class

Why we can't override "forwards animation"? I added a simple example. Cannot override even using !important.

// click and add the blue class
document.querySelector(".box").addEventListener("click", e => {
  e.target.classList.add("blue");
  console.log("blue class added");
})
.box {
  width: 80px;
  height: 80px;
  background: pink;
  animation: change-color .3s linear forwards;
}

@keyframes change-color {
  to {
    background: green;
  }
}

.blue {
  background: blue !important;
}
<div class="box"></div>

Upvotes: 1

Views: 304

Answers (1)

Temani Afif
Temani Afif

Reputation: 273797

This can be fixed using different methods.

If you are able to adjust the animation you can consider CSS variables:

// click and add the blue class
document.querySelector(".box").addEventListener("click", e => {
  e.target.classList.add("blue");
  console.log("blue class added");
})
.box {
  width: 80px;
  height: 80px;
  background: pink;
  animation: change-color .3s linear forwards;
}

@keyframes change-color {
  to {
    background: var(--c,green);
  }
}

.blue {
  --c: blue;
}
<div class="box"></div>

Or do it differently where you don't need the use of forwards

// click and add the blue class
document.querySelector(".box").addEventListener("click", e => {
  e.target.classList.add("blue");
  console.log("blue class added");
})
.box {
  width: 80px;
  height: 80px;
  background: green;
  animation: change-color .3s linear;
}

@keyframes change-color {
  from {
    background: pink;
  }
}

.blue {
  background: blue;
}
<div class="box"></div>

In case you cannot adjust the animation you can try to add another layer on the top (using box-shadow, pseudo element, etc)

// click and add the blue class
document.querySelector(".box").addEventListener("click", e => {
  e.target.classList.add("blue");
  console.log("blue class added");
})
.box {
  width: 80px;
  height: 80px;
  background: pink;
  animation: change-color .3s linear forwards;
}

@keyframes change-color {
  to {
    background: green;
  }
}

.blue {
  box-shadow:0 0 0 500px inset blue;
}
<div class="box"></div>


You can also only animate the background-color and add the blue coloration with a gradient:

// click and add the blue class
document.querySelector(".box").addEventListener("click", e => {
  e.target.classList.add("blue");
  console.log("blue class added");
})
.box {
  width: 80px;
  height: 80px;
  background-color: pink;
  animation: change-color .3s linear forwards;
}

@keyframes change-color {
  to {
    background-color: green;
  }
}

.blue {
  background-image:linear-gradient(blue,blue);
}
<div class="box"></div>

Upvotes: 2

Related Questions