Why isn’t my animation working?

Asked

Viewed 68 times

0

I’m creating an animation that was supposed to work in which it aims to appear and disappear the content of the paragraph, but nothing happens:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        #text {
            animation: anima1 1s linear;
        }

        @keyframes anima1 {
            0% {
                display: block;
            }

            100% {
                display: none;
            }
        }
    </style>
</head>
<body>
    <p id="text">Text</p>
</body>
</html>

What I’m doing wrong so the animation doesn’t work?

1 answer

2


CSS animations do not work with display. If you want the paragraph to be hidden after 1 second, you could even use a combination of visibility: hidden with Javascript, where Javascript would detect the end of the animation to apply a display: none in the element:

document.addEventListener("DOMContentLoaded", function(){
   const eventos = ["animationend", "webkitAnimationEnd", "oAnimationEnd", "MSAnimationEnd"];
   eventos.forEach(e=>{
      document.getElementById("text").addEventListener(e, function(){
         this.style.display = "none";
      });
   });
});
#text {
   animation: anima1 1s linear forwards;
}

@keyframes anima1 {
   100% {
      visibility: hidden;
   }
}
<p id="text">Text</p>
Qualquer coisa aqui

The visibility: hidden makes the element invisible, but it still takes up space on the page. Javascript detects when the CSS animation ends and applies the display: none.

However, if you are going to use Javascript, you do not need to use CSS and Javascript animation at the same time. Just use simpler Javascript with setTimeout:

document.addEventListener("DOMContentLoaded", function(){
   setTimeout(function(){
      document.getElementById("text").style.display = "none";
   }, 1000);
});
<p id="text">Text</p>
Qualquer coisa aqui

Where has the value 1000 is equal to 1 second. The time value of the setTimeout is in milliseconds. Then you just multiply the seconds you want by 1000 (e.g.: 5 seconds = 5000).

Now, if you want a transition effect, you could use opacity in place of visibility:

document.addEventListener("DOMContentLoaded", function(){
   const eventos = ["animationend", "webkitAnimationEnd", "oAnimationEnd", "MSAnimationEnd"];
   eventos.forEach(e=>{
      document.getElementById("text").addEventListener(e, function(){
         this.style.display = "none";
      });
   });
});
#text {
   animation: anima1 1s linear forwards;
}

@keyframes anima1 {
   100% {
      opacity: 0;
   }
}
<p id="text">Text</p>
Qualquer coisa aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.