Home > front end >  How do I trigger a css animation from js when I add the element dynamically?
How do I trigger a css animation from js when I add the element dynamically?

Time:12-10

How could I add an animation to a bubble window so it appears from the bottom to the top (from 0% to 100% of its height), it seems that the animation is not called.

let img = new Image();

img.onload = (e)=>{
    img.width = "170"; 
    img.height = "170";
    let el = document.createElement("div");
    el.classList.add("bubbleAppear");
    el.appendChild(img);
    el.style.position = "absolute";
    document.body.appendChild(el);
}
img.src = "imgs/window2.png";

and

.bubbleAppear {
            -webkit-animation: 1s linear 0s  fadeIn_bubble;
            animation: 1s linear 0s  fadeIn_bubble;
         }

        @-webkit-keyframes fadeIn_bubble { from { width:0%; } to { width:100%; }  }
        @keyframes fadeIn_bubble { from { width:100%; } to { width:0%; }  }

CodePudding user response:

You can do this by making your image hidden by default and use a separate event to animate its visibility.

CSS
===

#myImg {
  height: 0em;
  transition-property: height;
  transition-duration: 1s;
  transition-delay: 2s;
}

#myImg.show {
  height : 4em;
}

JavaScript
==========
//Add myImg to the DOM
myImg.onLoad(function() {
  myImg.classList.add("show");
});

You could also use setTimeout

=== Edit ===

Using max-height instead of height might be more ideal

CodePudding user response:

Maybe like this?

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <style>
      .bubbleAppear img {
        -webkit-animation: 1s linear 0s fadeIn_bubble;
        animation: 1s linear 0s fadeIn_bubble;
      }

      @-webkit-keyframes fadeIn_bubble {
        from {
          width: 100%;
        }
        to {
          width: 0%;
        }
      }
      @keyframes fadeIn_bubble {
        from {
          width: 0%;
        }
        to {
          width: 100%;
        }
      }
    </style>

    <script>
      let img = new Image();

      img.onload = (e) => {
        img.width = "170";
        img.height = "170";
        let el = document.createElement("div");
        el.classList.add("bubbleAppear");
        el.appendChild(img);
        el.style.position = "absolute";
        document.body.appendChild(el);
      };
      img.src = "https://lh3.googleusercontent.com/a-/AOh14GjtBVfGIhNHII2Xd_KCVxW2j1ED41wEpzGDqtoB8w=k-s48";
    </script>
  </body>
</html>
  • Related