akb10
akb10

Reputation: 83

How to replay this CSS animation each time a user clicks?

I've created a button that displays the text "Copied!" each time the user clicks on the "Copy" button. The way I've accomplished this is by assigning the animation to the relevant tag and by also using setTimeout to "reset" the animation. This way, when a user clicks the button a second or third time, the animation plays again.

However, I'm certain this is not an ideal solution because if a user clicks before setTimeout finishes, the button 'breaks' until 2500ms have passed. After that, it works again.

How can I refactor the CSS/JS so that the "Copied!" message displays each time the button is clicked? (Without being limited/delayed by a timeout)

  const copyURL = () => {
    const copyDiv = document.querySelector(".copyAlert")
    copyDiv.textContent = "Copied!";
    copyDiv.style.animationName = "disappear";
    copyDiv.style.animationDuration = "2.5s"; 
    setTimeout(function(){ 
    copyDiv.style.animationName = "none"; 
    }, 2400);

  };
.copyAlert {
  opacity: 0;
}

@keyframes disappear {
  30% {
    opacity: 0;
  }

  60% {
    opacity: 1;
  }

  100% {
    opacity: 0;
  }
}
<button onclick="copyURL()">Copy</button>

<span class="copyAlert"></span>

Upvotes: 3

Views: 3089

Answers (2)

Himanshu Saxena
Himanshu Saxena

Reputation: 370

If possible try with setTimeOut() function setTimeOut to change your text from Copy to Copied! [How to change the button text on click for a short duration only using javascript?

Upvotes: 0

fiter
fiter

Reputation: 773

1) Use animationend event
2) Use animate class for animation
3) Don't use JS to insert "Copied!" text, just write it in your html

const copyURL = () => {
  const copyDiv = document.querySelector('.copyAlert:not(.animate)')
  if(copyDiv) {
    copyDiv.classList.add('animate');
    copyDiv.addEventListener('animationend', () => copyDiv.classList.remove('animate') );
  }
};
.animate { animation: disappear 2.5s linear; }

.copyAlert { opacity: 0; }

@keyframes disappear {
  30%  { opacity: 0; }
  60%  { opacity: 1; }
  100% { opacity: 0; }
}
<button onclick="copyURL()">Copy</button>
<span class="copyAlert">Copied!</span>

Upvotes: 7

Related Questions