2

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?

0

1 Answer 1

5

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(
  [
    { // from parameters
      left: 0 + "px",   // you can set this dynamically
      top:  0 + "px"    // you can set this dynamically
    },
    { // to parameters
      left: 400 + "px", // you can set this dynamically
      top:  500 + "px"  // you can set this dynamically
    }
  ],
  {
    duration: 5000,
    iterations: Infinity
  }
);
#saved-test {
  width: 40px;
  height: 40px;
  background: red;
  position: fixed;
  z-index: 1000;
}
<div id="saved-test">

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.