Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

188
Views
I'm using click event to trigger CSS animation, why wouldn't the animation run again when clicked again?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!