Home > Software engineering >  How to apply different animation on the same text when two different buttons are clicked
How to apply different animation on the same text when two different buttons are clicked

Time:02-10

I have a button that when clicked will display a <p> text <p/> element and I gave it an animation (going from top to bottom) but now I created another button that when clicked will delete the text in the <p> element I want to add an animation for when that happens, but when I code the CSS to animate the text when deleted, it seems to override the previous animation.

Is there an if else statement in CSS or can I do it in JavaScript? This is vanilla JavaScript and CSS.

<button  onclick="Click()">click me</button>
<p id="appear" hidden>This text should appear on click</p>

<button  onclick="ClickRemove()">click me to delete message</button>
@keyframes buttonappear { 
  0% {top: 10px;}
  100% {top: 175px;}
}

#appear {
  position: absolute;
  top: 175px;
  animation-name: buttonappear;
  animation-duration: 2.5s;
}
const Click = () => {
  document.getElementById("appear").style.display = "block";
}

const ClickRemove = () => {
  document.getElementById("appear").style.display = "none";
}

What CSS or JS code can I use to animate the text when it disappears without overriding the previous animation?

CodePudding user response:

Instead of using a @keyframes animation, you can use the transition property and toggle a CSS class on the <p> element. Since you want to perform the animation in response to an action, transition works perfectly for this case. Also reversing states mid-animation is handled automatically.

Here's an example:

The approach here is to set the hidden styles on the <p> element and define a separate class (visible) that contains the visible styles. Depending on which button is clicked, the visible class will be added to or removed from the <p> element and the transition will animate between the two styles.

const message = document.querySelector("#message");

function clickShow() {
  message.classList.add("visible");
}

function clickRemove() {
  message.classList.remove("visible");
}
#message {
  position: absolute;
  opacity: 0;
  top: 10px;
  transition: 2.5s;
}

#message.visible {
  opacity: 1;
  top: 175px;
}
<button  onclick="clickShow()">click me</button>
<p id="message">This text should appear on click</p>

<button  onclick="clickRemove()">click me to delete message</button>

Actually the code above can be simplified quite a bit if you want by only using one button that just toggles the message, like this:

const message = document.querySelector("#message");

function toggleMessage() {
  message.classList.toggle("visible");
}
#message {
  position: absolute;
  opacity: 0;
  top: 10px;
  transition: 2.5s;
}

#message.visible {
  opacity: 1;
  top: 175px;
}
<button  onclick="toggleMessage()">click me</button>
<p id="message">This text should appear on click</p>

  •  Tags:  
  • Related