I'm new to web dev, I'm trying to get a better understanding on DOM.
The purpose of my code is to give an element some animation when a click event is triggered. Here's what I tried:
Code:
const svg = document.getElementById('svg');
const button = document.getElementById('button');
button.onclick = function() {
svg.style.animation = 'svg-color 5s linear 1 1s';
}
svg {
background-color: lightcyan;
}
@keyframes svg-color {
0% {
background-color: lightcyan;
}
50% {
background-color: skyblue;
}
100% {
background-color: steelblue;
}
}
<svg id="svg" width="300" height="300"></svg>
<button id="button">button</button>
It works on the first click event. But when I click the button again, the animation won't run again.
Is this issue due to DOM or the fact that I have set animation-iteration-count as 1 on CSS?
And if I set animation-iteration-count as infinite, is there a way to make the animation goes back to its start state and replay again on click event?
Nothing happens if you assign a style that's already set on the element.
You need to remove the style when the animation ends. That way, the style will be new the next time you click.
const svg = document.getElementById('svg');
const button = document.getElementById('button');
button.onclick = function() {
svg.style.animation = 'svg-color 5s linear 1 1s';
}
svg.addEventListener("animationend", (e) => e.target.style.animation = '');
svg {
background-color: lightcyan;
}
@keyframes svg-color {
0% {
background-color: lightcyan;
}
50% {
background-color: skyblue;
}
100% {
background-color: steelblue;
}
}
<svg id="svg" width="300" height="300"></svg>
<button id="button">button</button>