Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to manipulate CSS @keyframes through JavaScript?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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: 0,
      top: 0
    },
    {
      left: 400, // you can set it dynamically
      top: 500 // 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">
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading