How to create bouncing div animation with JavaScript?

Sometimes, we want to create bouncing div animation with JavaScript.

In this article, we’ll look at how to create bouncing div animation with JavaScript.

How to create bouncing div animation with JavaScript?

To create bouncing div animation with JavaScript, we can use the div’s animate method.

For instance, we write:

<div style='width: 50px; height: 50px; background-color: red; position: fixed'>

</div>

to add the div that we want to animate.

Then we write:

document.querySelector("div")
  .animate([{
      bottom: '5px'
    },
    {
      bottom: '15px'
    },
    {
      bottom: '20px'
    },
    {
      bottom: '0px'
    }
  ], {
    duration: 1000,
    iterations: Infinity
  });

to select the div with querySelector and call animate on it with an array of keyframes.

Each keyframe object has the CSS styles we want to apply to the div for each keyframe.

We set the duration to 1 second and iterations to Infinity to repeat the animation every second forever.

Conclusion

To create bouncing div animation with JavaScript, we can use the div’s animate method.