Home > OS >  How to manipulate CSS @keyframes through JavaScript?
How to manipulate CSS @keyframes through JavaScript?

Time:06-10

I have a simple CSS animation:

<div id="saved-test">

<style type="text/css">
    #saved-test {
        width:  40px; height:  40px;
        background:  red;
        position: fixed;
        top:  0; left: 0;
        animation-name: move-to-bottom;
        animation-duration: 5s;
        z-index:  1000;
    }


    @keyframes move-to-bottom {
      to {
        left:  400px;
        top:  500px;
      }
    }
</style>

This works, and it moves as I want nicely. The issue I have, is that I want to set the destination of this element to be different. It will be "moving" to a bottom nav bar, which means the destination left/top positions will vary depending on screen size.

Is it possible to modify the left and top value in the keyframe via Javascript, so it goes to a set position that I set dynamically?

CodePudding user response:

You can write the keyframe entirely with JavaScript as below, which gives you the ability to use dynamic values.

The Element interface's animate() method is a shortcut method which creates a new Animation, applies it to the element, then plays the animation. It returns the created Animation object instance. More and MDN's doc.

document.getElementById("saved-test").animate(
  [
    // étapes/keyframes
    {
      left: "0px",
      top: "0px"
    },
    {
      left: 400   "px", // you can set it dynamically
      top: 500  "px" // you can set it dynamically
    }
  ],
  {
    duration: 5000,
    iterations: Infinity
  }
);
#saved-test {
  width: 40px;
  height: 40px;
  background: red;
  position: fixed;
  z-index: 1000;
}
<div id="saved-test">

  • Related