I wanted to use @keyframes, so I did this:
div {
width: 100px;
height: 100px;
background: red;
position: relative;
animation: action 5s infinite;
}
@keyframes action {
0% {top: 0px;}
25% {top: 200px;}
75% {top: 50px}
100% {top: 100px;}
}
However, this code runs when the page loads. Is there a way to trigger the @keyframes at a certain time with js? eg.
for (var i = 0; i < 10; i++) {
//Do something
}
//Activate @keyframes
Thanks!
In CSS:
div {
// your div code
animation-play-state: paused;
}
In JS:
// do some stuff after the page loads (give your div an ID)
document.getElementById("myDiv").style.animationPlayState = "running";
If you want to trigger the animation using Javascript you just need to set the animation of the element.
div {
width: 100px;
height: 100px;
background: red;
position: relative;
}
@keyframes action {
0% {top: 0px;}
25% {top: 200px;}
75% {top: 50px}
100% {top: 100px;}
}
document.getElementByID('your-Elem').style.animation="action 5s infinite";
So in your case, I'd say give the element an ID (or just select all divs if thats what you're going for) and then run this line in your for loop.
You can separate animation definition to another css class and trigger it programmatically. Firstly, add class to your div e.g.:
<div class="test">
</div>
Create another css class where you define the animation:
div {
width: 100px;
height: 100px;
background: red;
position: relative;
}
.animate{
animation: action 5s infinite;
}
@keyframes action {
0% {top: 0px;}
25% {top: 200px;}
75% {top: 50px}
100% {top: 100px;}
}
Add this class to div element classList when you find it right:
for (let i = 0; i < 10; i++) {
//
}
document.querySelector('.test').classList.add('animate');