Fabio Torti
Fabio Torti

Reputation: 71

Javascript animation fires intermittently

I have a Math game with a function to calculate the correct answer. If user answer correctly I want to show an animated images. I was able to achieve this but the animation it self work basically one time yes and one time not.

Do I miss something?

function checkAnswer() {

  // Checks the answer against the first element in 
  // the returned calculateCorrectAnswer array

  let userAnswer = parseInt(document.getElementById('answer-box').value);
  let calculatedAnswer = calculateCorrectAnswer();
  let isCorrect = userAnswer === calculatedAnswer[0];

  if(isCorrect) {
     incrementScore();
     moveRight();
    
  } else {
    alert(`Awwww .... you answered ${userAnswer}. the correct answer was ${calculatedAnswer[0]} 😟`);
    incrementWrongAnswer();
  }

  runGame(calculatedAnswer[1]);
 
}


function moveRight() {
  let theImg = document.getElementById('myImg');
  let msg = document.getElementById('message');
  theImg.classList.toggle('fade-in');
  msg.classList.toggle('fade-in');
  
  
}

// My CSS

#myImg.fade-in {
  animation-name: fadeIn;               
    animation-duration: 2s;                 
    
}

@keyframes fadeIn {

  0% {opacity: 0;} 
    100% {opacity: 1;} 
}enter code here

Upvotes: 0

Views: 42

Answers (2)

Fabio Torti
Fabio Torti

Reputation: 71

find the solution, basically just removing the class and add again :)

 function moveRight() {
  let theImg = document.getElementById('myImg');
  let msg = document.getElementById('message');
  theImg.classList.remove('fade-in');
  void theImg.offsetWidth; 
  theImg.classList.toggle('fade-in');
  msg.classList.remove('fade-in');
  void msg.offsetWidth; 
  msg.classList.toggle('fade-in');
  
  
}

Upvotes: 1

V.Volkov
V.Volkov

Reputation: 739

In your case I'd use transition, instead of animation The code would look like that:

#myImg {
  opacity: 0;
  transition: opacity 2s linear;
    
}
#myImg.fade-in {
  opacity: 1;
}

Upvotes: 1

Related Questions