Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

190
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda