I have a growing list of divs. The user can click a button to append a new div to the bottom.
This list has a fade-in animation, this is so that the user can see when the list has been loaded (it gets data from a server).
When a new row gets added, I’d like to not have the fade-in animation.
I tried using:
div:last-child {
animation: none;
}
This works only the first time a new div has been added. On all the following additions, the animation gets applied regardless.
Please check this demo below to see what I mean:
function addRow(text) {
var d = document.createElement('div');
d.innerHTML = text;
var root = document.querySelector('main');
root.appendChild(d);
}
body {
background: #222;
}
main > div {
background: #444;
border: 1px solid green;
animation: fade-in 1s;
}
div:last-child {
background: #999;
animation: none;
}
@keyframes fade-in {
from { opacity: 0 }
to { opacity: 1 }
}
<main>
<div>1</div>
<div>2</div>
<div>3</div>
</main>
<button type="button" onclick="addRow('hello')">Add row</button>
How do I ensure the animation runs on the whole list the first time, but prevent it on subsequent additions?
Alternatively, you can set the initial state of your class to how you want the animation to end, then * initialize * it at from / 0% .
To stop a keyframe animation in CSS, you use the forwards value in the animation-fill-mode property.
To access the Accessibility features on your Android device open the Settings app . In the Settings app, select Accessibility from the list. Now scroll down to the Display section and select Remove Animations to set the toggle switch to On.
CSS animations emit events, so you can use the animationend event to intervene when the animation ends. const element = document. getElementById("element-to-be-animated"); element. addEventListener("animationend", () => { // Set your final state here.
One option changing a little bit the JS and CSS:
Add a class to the newly added elements to the list
d.className = "added";
Apply the animation only to the div
that don't have that class
main > div:not(.added) {
animation: fade-in 1s;
}
The initial div
don't have that class, so they will be animated when the page loads, but the div
that are added later (with the class name you specified) don't have any animation.
Here is a demo on how it would be based on your code:
function addRow(text) {
var d = document.createElement('div');
d.className = "added";
d.innerHTML = text;
var root = document.querySelector('main');
root.appendChild(d);
}
body {
background: #222;
}
main > div {
background: #444;
border: 1px solid green;
}
main > div:not(.added) {
animation: fade-in 1s;
}
div.added:last-child {
background: #999;
}
@keyframes fade-in {
from { opacity: 0 }
to { opacity: 1 }
}
<main>
<div>1</div>
<div>2</div>
<div>3</div>
</main>
<button type="button" onclick="addRow('hello')">Add row</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With