Update
Adding a delay solved my problem:
setTimeout(() => price.classList.add("fade-it"), 100);
Original question
I have a fade-in effect on background color that should be repeated from time to time initiated by me.
I'm using pure CSS:
<style>
@-webkit-keyframes yellow-fade {
from {
background: #f96;
}
to {
background: #fff;
}
}
@-moz-keyframes yellow-fade {
from {
background: #f96;
}
to {
background: #fff;
}
}
@keyframes yellow-fade {
from {
background: #f96;
}
to {
background: #fff;
}
}
.fade-it {
-webkit-animation: yellow-fade 1s ease-in-out 0s;
-moz-animation: yellow-fade 1s ease-in-out 0s;
-o-animation: yellow-fade 1s ease-in-out 0s;
animation: yellow-fade 1s ease-in-out 0s;
}
</style>
How do I restart this effect after it's already played once?
The code I have is not working after the first time:
var price = document.getElementById("price");
if (price.classList.contains("fade-it")) {
price.classList.remove("fade-it");
}
price.classList.add("fade-it");
You can accomplish this by removing the node from the DOM then adding it back. The append
function does exactly that, just append the element to it's parentNode
. Give the element it's own wrapper to be the parentNode
that way it will not be reordered with other sibling-elements.
const price = document.getElementById("price"); const btn = document.getElementById("fade-price"); const fade = function() { if (price.classList.contains("fade-it")) { price.classList.remove("fade-it"); } price.classList.add("fade-it"); } document.addEventListener("DOMContentLoaded", function() { fade() }); btn.addEventListener("click", function() { price.parentElement.append(price) });
@-webkit-keyframes yellow-fade { from { background: #f96; } to { background: #fff; } } @-moz-keyframes yellow-fade { from { background: #f96; } to { background: #fff; } } @keyframes yellow-fade { from { background: #f96; } to { background: #fff; } }.fade-it { -webkit-animation: yellow-fade 1s ease-in-out 0s; -moz-animation: yellow-fade 1s ease-in-out 0s; -o-animation: yellow-fade 1s ease-in-out 0s; animation: yellow-fade 1s ease-in-out 0s; }
<div> <h4 id="price">$9.99</h4> </div> <button id="fade-price"> fade </button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.