Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

198
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda